Sample code for 30+ languages & platforms
Zig 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 Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // 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.
    const mcp = try chilkat.Mcp.init();
    defer mcp.deinit();
    // mcp.AuthToken = "..."; // <-- only if the server requires a bearer token
    mcp.connect("https://mcp.deepwiki.com/mcp") catch {
        std.debug.print("{s}\n", .{try mcp.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Connected to MCP server: {s} (version {s})\n", .{ try mcp.getServerName(alloc), try mcp.getServerVersion(alloc) });

    // 2) Set up the AI conversation and register the MCP tools.
    const ai = try chilkat.Ai.init();
    defer ai.deinit();
    ai.setProvider("anthropic");
    // The API key should come from a secure source rather than being hard-coded.
    ai.setApiKey("AI_PROVIDER_API_KEY");
    ai.setModel("claude-sonnet-5");

    // Automatic tool use requires a conversation (not a stateless query).
    ai.newConvo("test_conversation", "You are a helpful assistant.  Use the available tools when they can help answer the question.", "") catch {
        std.debug.print("{s}\n", .{try ai.getLastErrorText(alloc)});
        return;
    };

    // 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.
    ai.useMcp(mcp, "deepwiki") catch {
        std.debug.print("{s}\n", .{try ai.getLastErrorText(alloc)});
        return;
    };

    // 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");

    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.") catch {
        std.debug.print("{s}\n", .{try ai.getLastErrorText(alloc)});
        return;
    };

    // 3) Start streaming.
    ai.setStreaming(true);
    ai.ask("text") catch {
        std.debug.print("{s}\n", .{try ai.getLastErrorText(alloc)});
        return;
    };

    // 4) Drive the streaming event loop.
    const sb_event_name = try chilkat.StringBuilder.init();
    defer sb_event_name.deinit();
    const sb_delta = try chilkat.StringBuilder.init();
    defer sb_delta.deinit();
    const sb_full_response = try chilkat.StringBuilder.init();
    defer sb_full_response.deinit();
    var b_conversation_done: bool = false;
    var b_tool_call_pending: bool = false;
    const b_case_sensitive = true;
    const b_abort = false;
    var loop_guard: i32 = 0;
    var result: i32 = 0;

    while ((!b_conversation_done) and (loop_guard < 8000)) {
        loop_guard = loop_guard + 1;
        result = ai.pollAi(b_abort);
        if (result < 0) {
            std.debug.print("{s}\n", .{try ai.getLastErrorText(alloc)});
            return;
        }

        if (result == 0) {
            // No event ready yet.
            ai.sleepMs(100);
        } else {
            ai.nextAiEvent(5000, sb_event_name, sb_delta) catch {
                std.debug.print("{s}\n", .{try ai.getLastErrorText(alloc)});
                return;
            };

            if (sb_event_name.contentsEqual("js_function_call", b_case_sensitive)) {
                // (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.
                std.debug.print("[tool call requested]\n", .{});
                std.debug.print("{s}\n", .{try sb_delta.getAsString(alloc)});
                ai.streamingJsToolCall(sb_delta) catch {
                    std.debug.print("{s}\n", .{try ai.getLastErrorText(alloc)});
                    return;
                };

                b_tool_call_pending = true;
            } else {
                if (sb_event_name.contentsEqual("null_terminator", b_case_sensitive)) {
                    // (c) This streamed turn has finished.
                    if (b_tool_call_pending) {
                        // Continue the conversation so the model can use the tool result.  No new
                        // InputAddText -- the tool result is already in the transcript.
                        b_tool_call_pending = false;
                        ai.ask("text") catch {
                            std.debug.print("{s}\n", .{try ai.getLastErrorText(alloc)});
                            return;
                        };
                    } else {
                        b_conversation_done = true;
                    }
                } else {
                    // (b) An "empty" event reports nothing this poll.  (d) Any other event is a normal
                    // streamed text delta, which we display and accumulate.
                    if (!sb_event_name.contentsEqual("empty", b_case_sensitive)) {
                        std.debug.print("Event: {s}  Delta: {s}\n", .{ try sb_event_name.getAsString(alloc), try sb_delta.getAsString(alloc) });
                        sb_full_response.appendSb(sb_delta) catch {};
                    }
                }
            }
        }
    }

    std.debug.print("Final streamed response:\n", .{});
    std.debug.print("{s}\n", .{try sb_full_response.getAsString(alloc)});
    std.debug.print("----\n", .{});

    // (Optional) The full transcript, including the tool call and its result.
    const convo_json = try chilkat.JsonObject.init();
    defer convo_json.deinit();
    convo_json.setEmitCompact(false);
    ai.exportConvo("test_conversation", convo_json) catch {
        std.debug.print("{s}\n", .{try ai.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Full Conversation:\n", .{});
    std.debug.print("{s}\n", .{try convo_json.emit(alloc)});

    // 5) Close the MCP session.
    mcp.close() catch {
        std.debug.print("{s}\n", .{try mcp.getLastErrorText(alloc)});
        return;
    };
}