Text generation · Plug MCP into a completion4 / 8
  1. 01
  2. 02
  3. 03
  4. 05
  5. 06
  6. 07
  7. 08

Plug MCP into a completion

Example on GitHub(packages/sdk/examples/mcp-websearch.ts)

Now that we know how to wire tools in by hand, let's see how MCP makes it automatic.

MCP (Model Context Protocol) is a standard way for the model to call external tools. We run an MCP server (search, file access, a database client), hand the SDK a Client from @modelcontextprotocol/sdk/client/index.js, and the SDK routes the model's tool calls through it automatically.

With an MCP server, the SDK reads the tool list at call time and adapts on its own, with no per-model schema rewrites. The lesson prefills the client setup and the loadModel call, so the only thing left to figure out is how the client threads into completion().

The mcp field is the only piece of wiring that ties an MCP client into a completion call. Once it's in, the SDK treats MCP-backed tools the same as native ones. A wired-up call looks like:

const result = completion({
  modelId,
  history: [
    { role: "user", content: "What's the current weather in New York?" },
  ],
  mcp: [{ client: mcpClient, includeResources: false }],
  stream: true,
  captureThinking: true,
});

The event loop is the same as in the tool-calls lesson, since the SDK fires identical toolCall events whether the tool is native or MCP-backed:

for await (const event of result.events) {
  if (event.type === "toolCall") {
    console.log(`▸ Tool: ${event.call.name}(${JSON.stringify(event.call.arguments)})`);
  }
  if (event.type === "contentDelta") {
    process.stdout.write(event.text);
  }
}

When the sampled output is a tool call from the MCP server, the SDK routes the call through mcpClient. We see the same toolCall events as for native tools.

Note: captureThinking: true is the option the first lesson in this chapter introduced. The model's thinking arrives on thinkingDelta events and stays out of the contentDelta stream the tool call comes from. The lesson's loop ignores thinkingDelta so the runner's OUTPUT panel only shows the tool calls and the final answer.

Note: MCP needs @modelcontextprotocol/sdk installed in your project. The SDK does not bundle it.

Put it to the test

  1. Install @modelcontextprotocol/sdk. The editor prefills a Client connected to npx -y @oevortex/ddg_search as a starter.
  2. Call completion({ modelId, history, stream: true, captureThinking: true, mcp: [{ client: mcpClient, includeResources: false }] }) and iterate result.events, logging toolCall events and writing contentDelta tokens to stdout. The loop ignores thinkingDelta so the runner's OUTPUT panel only shows the tool calls and the final answer. Then await mcpClient.close().
index.ts

$ Run your code to see results

$