Sample code for 30+ languages & platforms
Lazarus Pascal Requires Chilkat v11.6.0+

Streaming End-to-End MCP Tool Use with an AI Model

See more AI Examples

Demonstrates Ai.UseMcp in a streaming Model Context Protocol (MCP) workflow. This is the same idea as the non-streaming MCP example, but the answer is streamed token-by-token and the automatic MCP tool call is driven by the application's event loop rather than happening invisibly inside Ask.

A tool-using conversation spans more than one streamed turn. In the first turn the model streams a js_function_call event; the example hands that event's JSON to StreamingJsToolCall, which routes MCP tools to the server and appends the result to the transcript, and the turn ends with null_terminator. The example then calls Ask again (with no new input, since the tool result is already in the transcript) so the model can continue and stream its final answer. The loop ends when a streamed turn finishes with no tool call outstanding.

Tip: Code to parse the returned JSON can be generated with Chilkat's online tool at https://tools.chilkat.io/jsonParse.

Background. Automatic tool use requires a conversation (created with NewConvo); it cannot be used with a stateless query. The event loop polls with PollAi and reads events with NextAiEvent: a js_function_call event carries a tool request, empty means nothing to report this poll, and null_terminator marks the end of a streamed turn. The Mcp object must stay connected and in scope for the whole conversation. This example uses DeepWiki, a free, public, no-authentication Streamable HTTP MCP server; swap in any URL, setting AuthToken before Connect if a bearer token is required.
Using multiple MCP servers. More than one MCP server can be used in the same conversation. Connect each server and call UseMcp once per server — one call per MCP server — giving each a distinct prefix (for example deepwiki, weather, github) so tools from different servers never collide.

Chilkat Lazarus Pascal Downloads

Lazarus Pascal
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Mcp,
  Chilkat.StringBuilder,
  Chilkat.Ai,
  Chilkat.JsonObject;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  mcp: TMcp;
  ai: TAi;
  sbEventName: TStringBuilder;
  sbDelta: TStringBuilder;
  sbFullResponse: TStringBuilder;
  bConversationDone: Boolean;
  bToolCallPending: Boolean;
  bCaseSensitive: Boolean;
  bAbort: Boolean;
  loopGuard: Integer;
  result: Integer;
  convoJson: TJsonObject;

begin
  success := False;

  //  Streaming, end-to-end MCP example.  Same idea as the non-streaming MCP example, but the answer is
  //  streamed token-by-token, and the automatic MCP tool call is driven by the application's event loop
  //  instead of happening invisibly inside Ask.
  //  
  //  A tool-using conversation spans more than one streamed turn:
  //  
  //    turn 1:  the model streams a "js_function_call" event (it wants a tool).  We hand that event's
  //             JSON to StreamingJsToolCall, which routes MCP tools to the server (Mcp.CallTool) and
  //             appends the result to the transcript.  The turn then ends with "null_terminator".
  //    turn 2:  we call Ask again (no new input -- the tool result is already in the transcript) so the
  //             model can continue.  It streams the final answer and ends with "null_terminator", with
  //             no pending tool call.
  //  
  //  The loop ends when a streamed turn finishes with no tool call outstanding.
  //  
  //  MCP server: DeepWiki -- a free, public, no-authentication Streamable HTTP server that answers
  //  questions about public GitHub repositories.  Swap in any URL; set mcp.AuthToken before Connect if
  //  it needs a bearer token.

  //  1) Connect to the MCP server.
  mcp := TMcp.Create;
  //  mcp.AuthToken = "...";   // <-- only if the server requires a bearer token
  success := mcp.Connect('https://mcp.deepwiki.com/mcp');
  if (success = False) then
    begin
      WriteLn(mcp.LastErrorText);
      Exit;
    end;

  WriteLn('Connected to MCP server: ' + mcp.ServerName + ' (version ' + mcp.ServerVersion + ')');

  //  2) Set up the AI conversation and register the MCP tools.
  ai := TAi.Create;
  ai.Provider := 'anthropic';
  //  The API key should come from a secure source rather than being hard-coded.
  ai.ApiKey := 'AI_PROVIDER_API_KEY';
  ai.Model := 'claude-sonnet-5';

  //  Automatic tool use requires a conversation (not a stateless query).
  success := ai.NewConvo('test_conversation','You are a helpful assistant.  Use the available tools when they can help answer the question.','');
  if (success = False) then
    begin
      WriteLn(ai.LastErrorText);
      Exit;
    end;

  //  Namespace the server's tools with "deepwiki" -- e.g. "deepwiki_ask_question".  The Mcp object must
  //  stay connected and in scope for the whole conversation.
  success := ai.UseMcp(mcp,'deepwiki');
  if (success = False) then
    begin
      WriteLn(ai.LastErrorText);
      Exit;
    end;

  //  Multiple MCP servers can be used in the same conversation.  Connect each server and call UseMcp
  //  once per server, giving each a distinct prefix so their tool names cannot collide.  For example:
  //      success = ai.UseMcp(mcpWeather,"weather");
  //      success = ai.UseMcp(mcpGitHub,"github");

  success := ai.InputAddText('Use the available tools to look up the GitHub repository "modelcontextprotocol/modelcontextprotocol", then give me a brief, sourced summary of which transports the Model Context Protocol defines.');
  if (success = False) then
    begin
      WriteLn(ai.LastErrorText);
      Exit;
    end;

  //  3) Start streaming.
  ai.Streaming := True;
  success := ai.Ask('text');
  if (success = False) then
    begin
      WriteLn(ai.LastErrorText);
      Exit;
    end;

  //  4) Drive the streaming event loop.
  sbEventName := TStringBuilder.Create;
  sbDelta := TStringBuilder.Create;
  sbFullResponse := TStringBuilder.Create;
  bConversationDone := False;
  bToolCallPending := False;
  bCaseSensitive := True;
  bAbort := False;
  loopGuard := 0;
  result := 0;

  while (bConversationDone <> True) and (loopGuard < 8000) do
    begin
      loopGuard := loopGuard + 1;
      result := ai.PollAi(bAbort);
      if (result < 0) then
        begin
          WriteLn(ai.LastErrorText);
          Exit;
        end;
      if (result = 0) then
        begin
          //  No event ready yet.
          ai.SleepMs(100);
        end
      else
        begin
          success := ai.NextAiEvent(5000,sbEventName,sbDelta);
          if (success = False) then
            begin
              WriteLn(ai.LastErrorText);
              Exit;
            end;

          if (sbEventName.ContentsEqual('js_function_call',bCaseSensitive) = True) then
            begin
              //  (a) The model is requesting a tool call.  sbDelta holds the function-call JSON.
              //  StreamingJsToolCall runs the tool -- routing MCP tools to the server -- and appends the
              //  result to the transcript.  It must be called before this turn's null_terminator.
              WriteLn('[tool call requested]');
              WriteLn(sbDelta.GetAsString());
              success := ai.StreamingJsToolCall(sbDelta);
              if (success = False) then
                begin
                  WriteLn(ai.LastErrorText);
                  Exit;
                end;
              bToolCallPending := True;
            end
          else
            begin
              if (sbEventName.ContentsEqual('null_terminator',bCaseSensitive) = True) then
                begin
                  //  (c) This streamed turn has finished.
                  if (bToolCallPending = True) then
                    begin
                      //  Continue the conversation so the model can use the tool result.  No new
                      //  InputAddText -- the tool result is already in the transcript.
                      bToolCallPending := False;
                      success := ai.Ask('text');
                      if (success = False) then
                        begin
                          WriteLn(ai.LastErrorText);
                          Exit;
                        end;
                    end
                  else
                    begin
                      bConversationDone := True;
                    end;
                end
              else
                begin
                  //  (b) An "empty" event reports nothing this poll.  (d) Any other event is a normal
                  //  streamed text delta, which we display and accumulate.
                  if (sbEventName.ContentsEqual('empty',bCaseSensitive) <> True) then
                    begin
                      WriteLn('Event: ' + sbEventName.GetAsString() + '  Delta: ' + sbDelta.GetAsString());
                      sbFullResponse.AppendSb(sbDelta);
                    end;
                end;
            end;
        end;
    end;

  WriteLn('Final streamed response:');
  WriteLn(sbFullResponse.GetAsString());
  WriteLn('----');

  //  (Optional) The full transcript, including the tool call and its result.
  convoJson := TJsonObject.Create;
  convoJson.EmitCompact := False;
  success := ai.ExportConvo('test_conversation',convoJson);
  if (success = False) then
    begin
      WriteLn(ai.LastErrorText);
      Exit;
    end;
  WriteLn('Full Conversation:');
  WriteLn(convoJson.Emit());

  //  5) Close the MCP session.
  success := mcp.Close();
  if (success = False) then
    begin
      WriteLn(mcp.LastErrorText);
      Exit;
    end;


  mcp.Free;
  ai.Free;
  sbEventName.Free;
  sbDelta.Free;
  sbFullResponse.Free;
  convoJson.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.