claude-code icon indicating copy to clipboard operation
claude-code copied to clipboard

[BUG] Claude Code SDK: SDK MCP server faills to connect due to closed stream

Open codylund opened this issue 1 year ago • 26 comments

Environment

  • Platform (select one):
    • [ ] Anthropic API
    • [ ] AWS Bedrock
    • [ ] Google Vertex AI
    • [x] Other: Claude Code SDK
  • Claude CLI version: 1.0.96
  • Operating System: macOS 15.1
  • Terminal: Terminal App

Bug Description

The new SDK MCP server type does not work with basic string prompts. Running with DEBUG=true, I see the following error:

[ERROR] MCP server "test" Failed to connect SDK MCP server: Error: Stream closed

Steps to Reproduce

Below is a basic sample:

import { createSdkMcpServer, query, tool } from "@anthropic-ai/claude-code";
import { z } from "zod";

const mcp = createSdkMcpServer({
  name: "test",
  tools: [
    tool(
      "add",
      "Add two numbers",
      {
        a: z.number(),
        b: z.number(),
      },
      async ({ a, b }) => {
        return {
          content: [
            {
              type: "text",
              text: `${a + b}`,
            },
          ],
        };
      }
    ),
  ],
});

for await (const message of query({
  //prompt: generateMessages(),
  prompt: "Use the tool to add 1 and 2 and return the result.",
  options: {
    mcpServers: {
      test: mcp,
    },
    allowedTools: ["mcp__test__add"],
  },
})) {
  console.log(JSON.stringify(message));
}

Expected Behavior

Prompt should run with successful connection and access to the SDK MCP server.

Actual Behavior

Claude CLI process exits with an error.

codylund avatar Aug 28 '25 03:08 codylund

I encountered the same issue today and was able to work around it with a minimal adjustment:

  1. Refactored into an MCP Server using @modelcontextprotocol/sdk (this was straightforward since the code format is nearly identical).
  2. Updated the mcpServers definition as shown below.

Before:

for await (const message of query({
    prompt: ...,
    options: {
        allowedTools: [
            ...
            'mcp__test',
        ],
        mcpServers: {
            'test': testMcpServer,
        },
    },
})) {

After:

for await (const message of query({
    prompt: ...,
    options: {
        allowedTools: [
            ...
            'mcp__test',
        ],
        mcpServers: {
            'test': {
                type: 'stdio',
                command: 'npx',
                args: ['-y', 'tsx', 'src/mcps/test.ts'],
            },
        },
    },
})) {

With this approach, I was able to get things running in under five minutes with only minimal changes. Depending on your setup, you may need to use a built JS artifact instead of tsx, but for my use case this was sufficient.

selenehyun avatar Aug 29 '25 03:08 selenehyun

@selenehyun I'm glad to hear this works for you, but this does not run the local MCP server in the same process. That's my main motivation for using the SDK type.

codylund avatar Aug 29 '25 12:08 codylund

This still reproduces with v1.0.96...

codylund avatar Aug 29 '25 12:08 codylund

same issue for me

bolahanna44 avatar Aug 31 '25 14:08 bolahanna44

Broken with v1.0.98 as well

ShuangLiu1992 avatar Aug 31 '25 18:08 ShuangLiu1992

same issue

xpluscal avatar Sep 01 '25 09:09 xpluscal

same issue , even without the allowedTools prop

tom-n-terra avatar Sep 01 '25 09:09 tom-n-terra

Trying the example here https://docs.anthropic.com/en/docs/claude-code/sdk/sdk-typescript#creating-custom-tools but it doesn't seem to work either:

[ERROR] MCP server "my-custom-tools" Failed to connect SDK MCP server: Error: Stream closed

tariqkb avatar Sep 01 '25 17:09 tariqkb

FWIW, I have the SDK MCP server type working in a single Bun-based project using v1.0.98, but I can't get it working in any other project. I have no idea why it works yet...

codylund avatar Sep 02 '25 15:09 codylund

@codylund by any other project, do you mean projects using node or deno?

ShuangLiu1992 avatar Sep 02 '25 15:09 ShuangLiu1992

@ShuangLiu1992 Just any other Bun-based projects in general. I don't know what's special about the project where the SDK MCP server is functional. It's an overall basic set up and is very similar to the example I added in my original post. It makes me suspect some kind of obscure race condition in the Claude Code SDK.

codylund avatar Sep 02 '25 15:09 codylund

It seems to still be an issue in v1.0.105

adamk-au avatar Sep 04 '25 21:09 adamk-au

Same issue here

kmaillet avatar Sep 05 '25 14:09 kmaillet

Running into this bug as well!

will-dayai avatar Sep 05 '25 20:09 will-dayai

Found a workaround

import { createSdkMcpServer, query, tool } from "@anthropic-ai/claude-code"
import { z } from "zod/v3"

const options = {
  name: "my-custom-tools",
  version: "1.0.0",
  tools: [
    tool(
      "calculate_compound_interest",
      "Calculate compound interest for an investment",
      {
        principal: z.number().describe("Initial investment amount"),
        rate: z.number().describe("Annual interest rate (as decimal, e.g., 0.05 for 5%)"),
        time: z.number().describe("Investment period in years"),
        n: z.number().default(12).describe("Compounding frequency per year"),
      },
      async args => {
        console.log("calculate_compound_interest was called")
        
        const amount = args.principal * (1 + args.rate / args.n) ** (args.n * args.time)
        const interest = amount - args.principal

        return {
          content: [
            {
              type: "text",
              text: `Final amount: $${amount.toFixed(2)}\nInterest earned: $${interest.toFixed(2)}`,
            },
          ],
        }
      },
    ),
  ],
}

const customServer = createSdkMcpServer(options)

function userMessage(content) {
  return {
    type: "user",
    message: { role: "user", content: content },
  }
}

async function* prompt() {
  yield userMessage("Calculate compound interest for $10,000 at 5% for 10 years using the calculate_compound_interest tool")
  await new Promise(res => setTimeout(res, 10000))
}

for await (const message of query({
  prompt: prompt(),
  options: {
    permissionMode: "bypassPermissions",
    mcpServers: {
      "my-custom-tools": customServer,
    },
    maxTurns: 3,
  },
})) {
  if (message.type === "result") {
    console.log(message.result)
  }
}

The key is keeping the input stream artificially open via the await new Promise(res => setTimeout(res, 10000)) sleep. It isn't ideal, but there is likely a better workaround that closes the input stream once claude-code returns the result.

tariqkb avatar Sep 07 '25 16:09 tariqkb

Looks like this was fixed in the Python Claude Code SDK: https://github.com/anthropics/claude-code-sdk-python/pull/157

arthurgousset avatar Sep 09 '25 13:09 arthurgousset

same issue

xujialiang avatar Sep 10 '25 23:09 xujialiang

same issue

stevenzg avatar Sep 10 '25 23:09 stevenzg

I encountered the same issue today and was able to work around it with a minimal adjustment:

  1. Refactored into an MCP Server using @modelcontextprotocol/sdk (this was straightforward since the code format is nearly identical).
  2. Updated the mcpServers definition as shown below.

Before:

for await (const message of query({ prompt: ..., options: { allowedTools: [ ... 'mcp__test', ], mcpServers: { 'test': testMcpServer, }, }, })) { After:

for await (const message of query({ prompt: ..., options: { allowedTools: [ ... 'mcp__test', ], mcpServers: { 'test': { type: 'stdio', command: 'npx', args: ['-y', 'tsx', 'src/mcps/test.ts'], }, }, }, })) { With this approach, I was able to get things running in under five minutes with only minimal changes. Depending on your setup, you may need to use a built JS artifact instead of tsx, but for my use case this was sufficient.

work for me

xujialiang avatar Sep 11 '25 16:09 xujialiang

await new Promise(res => setTimeout(res, 10000))

Works for me as a workaround. Thanks for sharing @tariqkb ❤️

arthurgousset avatar Sep 15 '25 13:09 arthurgousset