[BUG] Claude Code SDK: SDK MCP server faills to connect due to closed stream
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.
I encountered the same issue today and was able to work around it with a minimal adjustment:
- Refactored into an MCP Server using
@modelcontextprotocol/sdk(this was straightforward since the code format is nearly identical). - Updated the
mcpServersdefinition 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 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.
This still reproduces with v1.0.96...
same issue for me
Broken with v1.0.98 as well
same issue
same issue , even without the allowedTools prop
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
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 by any other project, do you mean projects using node or deno?
@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.
It seems to still be an issue in v1.0.105
Same issue here
Running into this bug as well!
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.
Looks like this was fixed in the Python Claude Code SDK: https://github.com/anthropics/claude-code-sdk-python/pull/157
same issue
same issue
I encountered the same issue today and was able to work around it with a minimal adjustment:
- Refactored into an MCP Server using
@modelcontextprotocol/sdk(this was straightforward since the code format is nearly identical).- Updated the
mcpServersdefinition 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
await new Promise(res => setTimeout(res, 10000))
Works for me as a workaround. Thanks for sharing @tariqkb ❤️