Skip to content

Commit 21291c2

Browse files
authored
Merge pull request #33 from code-rabi/claude/project-thread-62lb2t
fix: reject STATIC clients whose startup toolsets failed to load
2 parents 9e7e8a0 + 633f286 commit 21291c2

10 files changed

Lines changed: 239 additions & 9 deletions

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,14 @@ Releases before 0.7.0 are described in [GitHub Releases](https://github.com/code
1111
- `http.allowedOrigins` validates the `Origin` header on the `/mcp` endpoints, as the MCP spec requires. A request with an `Origin` outside the list gets `403`; requests without an `Origin` header are always allowed. When `cors` is on, only the listed origins get CORS access. Not set by default, so existing deployments behave as before.
1212
- **Migration:** none needed. To turn it on, pass `http: { allowedOrigins: ["https://app.example.com"] }`.
1313

14+
### Breaking
15+
16+
- `ServerOrchestrator.isReady()` now returns `false`, and `ensureReady()` throws, when registering a startup toolset's tools fails (for example a duplicate tool name, within a toolset or across toolsets when `namespaceToolsWithSetKey` is off). It used to report ready. As a result `createMcpServer` rejects at startup for such a catalog in STATIC mode, where it used to start with the partial toolset. Fix the catalog (rename or remove the duplicate tool) before upgrading. `enableToolset` results (and the `enable_toolset` meta-tool output) gain an optional `code` on that failure. Toolsets refused before registration (exposure policy, duplicate names in `startup.toolsets`) and module loader errors do not count as failures.
17+
18+
### Fixed
19+
20+
- A STATIC client whose startup toolsets fail to load now gets a JSON-RPC error (`-32603`, HTTP 500) on `initialize` instead of connecting with only some of its tools. The failed bundle is dropped, so the client's next `initialize` retries the load.
21+
1422
## [0.7.0]
1523

1624
### Breaking

‎src/core/AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Central orchestration layer. Manages toolset lifecycle, tool registration, and s
1919
5. **Toolset added to activeToolsets AFTER registration** — All tools must register successfully before toolset is marked active. Partial failures leave the toolset inactive but orphaned tools remain registered (MCP limitation).
2020
6. **`enableToolsets()` batches notifications** — Calls `enableToolset(name, skipNotification=true)` per toolset, sends one `tools/list_changed` notification at the end.
2121
7. **JSON Schema `inputSchema` uses `registerTool` with a passthrough object** — The SDK rejects plain JSON Schema as a tool schema. Zod raw shapes and schemas are passed to `registerTool` as is. Clients see an open object schema for JSON Schema tools, not the declared one.
22+
8. **Failed tool registration at startup makes the orchestrator not ready** — `enableToolsets()` reports failures in its result and never throws. A failure that carries a `code` (set when enabling threw, normally while registering the toolset's tools, e.g. a tool name collision) becomes `initError`, so `isReady()` is `false` and `ensureReady()` throws. Refusals made before any registration (invalid name, already enabled, exposure policy) carry no code and are ignored. Module loader errors are also ignored: `ModuleResolver` logs them and continues.
2223

2324
## Enable Toolset Flow
2425

‎src/core/DynamicToolManager.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import type {
77
ToolSetDefinition,
88
ToolingErrorCode,
99
} from "../types/index.js";
10+
import { ToolingError } from "../errors/ToolingError.js";
1011
import { ModuleResolver } from "../mode/ModuleResolver.js";
1112
import { ToolRegistry } from "./ToolRegistry.js";
1213
import type { DynamicToolManagerOptions } from "./core.types.js";
@@ -77,12 +78,12 @@ export class DynamicToolManager {
7778
* Enables a single toolset by name.
7879
* @param toolsetName - The name of the toolset to enable
7980
* @param skipNotification - If true, skips the tool list change notification
80-
* @returns Result object with success status and message
81+
* @returns Result object with success status and message; `code` is set only when enabling threw, normally while registering the toolset's tools
8182
*/
8283
public async enableToolset(
8384
toolsetName: string,
8485
skipNotification = false
85-
): Promise<{ success: boolean; message: string }> {
86+
): Promise<{ success: boolean; message: string; code?: ToolingErrorCode }> {
8687
const validation = this.validateToolsetForEnable(toolsetName);
8788
if ("message" in validation) return validation;
8889

@@ -116,6 +117,8 @@ export class DynamicToolManager {
116117
message: `Failed to enable toolset '${sanitized}': ${
117118
error instanceof Error ? error.message : "Unknown error"
118119
}`,
120+
// Only this path sets a code; ServerOrchestrator treats it as "enabling threw"
121+
code: error instanceof ToolingError ? error.code : "E_INTERNAL",
119122
};
120123
}
121124
}

‎src/core/ServerOrchestrator.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -83,10 +83,23 @@ export class ServerOrchestrator {
8383
initial: string[] | "ALL" | undefined
8484
): Promise<void> {
8585
try {
86-
if (initial === "ALL") {
87-
await this.manager.enableToolsets(this.resolver.getAvailableToolsets());
88-
} else if (Array.isArray(initial) && initial.length > 0) {
89-
await this.manager.enableToolsets(initial);
86+
const names =
87+
initial === "ALL"
88+
? this.resolver.getAvailableToolsets()
89+
: Array.isArray(initial)
90+
? initial
91+
: [];
92+
if (names.length > 0) {
93+
// enableToolsets reports failures in its result instead of throwing.
94+
// Only a failure while registering tools carries a code; refusals made
95+
// before any registration (policy, already enabled) leave nothing partial.
96+
const { results } = await this.manager.enableToolsets(names);
97+
const failures = results.filter((r) => !r.success && r.code);
98+
if (failures.length > 0) {
99+
throw new Error(
100+
`Failed to enable startup toolsets: ${failures.map((r) => r.message).join("; ")}`
101+
);
102+
}
90103
}
91104
} catch (error) {
92105
this.initError =

‎src/http/AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ Provides Fastify-based HTTP transport for the MCP protocol. Handles SSE streams,
3838
→ disconnectServer() — closes the bundle server's current transport (stale same-client connection)
3939
→ Set transport.onclose BEFORE server.connect() (SDK 1.26+ chain requirement)
4040
→ await bundle.orchestrator.isReady() — STATIC bundles preload tools async; SDK refuses capability registration after connect
41+
→ not ready → drop the bundle from the cache, respond 500 / JSON-RPC -32603; never connect with partial tools (no negative caching: each retry re-runs the module loaders)
4142
→ server.connect(transport) — throws "Already connected" if above steps missed
4243
→ Generate session ID, store in bundle.sessions via onsessioninitialized
4344

‎src/http/FastifyTransport.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,23 @@ export class FastifyTransport {
256256
try {
257257
// STATIC bundles preload toolsets asynchronously; the SDK refuses to
258258
// register tool capabilities once connected, so wait for them first.
259-
await bundle.orchestrator.isReady();
259+
const ready = await bundle.orchestrator.isReady();
260+
if (!ready) {
261+
// A failed preload is cached on the orchestrator for good, so drop
262+
// the bundle and let the client's next initialize start a fresh one.
263+
if (this.clientCache.get(cacheKey) === bundle) {
264+
this.clientCache.delete(cacheKey);
265+
}
266+
reply.code(500);
267+
return {
268+
jsonrpc: "2.0",
269+
error: {
270+
code: -32603,
271+
message: "Failed to load toolsets for this client.",
272+
},
273+
id: null,
274+
};
275+
}
260276
await bundle.server.connect(transport);
261277
} catch (error) {
262278
reply.code(500);

‎src/server/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Factory functions for creating MCP servers. Provides standard and permission-bas
1717
2. **Every client gets its own server, in both modes** — The MCP SDK binds one `McpServer` to one transport, so a shared STATIC server made each new client disconnect the previous one. STATIC client orchestrators preload the startup toolsets with the client's merged session context. The base server/orchestrator only serves validation at startup and the `/tools` status endpoint.
1818
3. **Permission-based servers reject `startup` field** — Throws if `startup` provided. Toolsets come from permissions, not config.
1919
4. **Permission-based sanitizes exposure policy** — `sanitizeExposurePolicyForPermissions` strips allowlist/denylist/maxActiveToolsets with warnings.
20-
5. **`ensureReady()` before transport start** — STATIC mode waits for the base toolset initialization to complete (fail-fast). Per-client readiness is awaited by the transport before `connect()`.
20+
5. **`ensureReady()` before transport start** — STATIC mode waits for the base toolset initialization to complete (fail-fast). Per-client readiness is awaited by the transport before `connect()`; a client whose preload failed gets a JSON-RPC error, not a partially loaded server.
2121
6. **Orchestrator built via conditional builder calls** — Optional fields (`exposurePolicy`, `startup`) passed to builder only when defined. Never use `!` to coerce.
2222

2323
## Notifier Pattern

‎tests/e2e/staticMode.e2e.test.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,84 @@ describe("STATIC mode E2E", () => {
242242
});
243243
});
244244

245+
describe("when a client's toolsets fail to load", () => {
246+
let server: Awaited<ReturnType<typeof createMcpServer>>;
247+
let port: number;
248+
let flakyAttempts = 0;
249+
250+
beforeAll(async () => {
251+
port = await getAvailablePort();
252+
server = await createMcpServer({
253+
createServer: () =>
254+
new McpServer({
255+
name: "test-static-failing-preload",
256+
version: "1.0.0",
257+
}),
258+
catalog: sessionContextCatalog,
259+
moduleLoaders: {
260+
// Loads fine for the startup check (no token). For "bad" it returns
261+
// two tools with one name, so registration fails halfway through.
262+
tenant: async (ctx: any) => {
263+
const tools = await sessionContextModuleLoaders.tenant(ctx);
264+
if (ctx?.API_TOKEN === "bad") return [...tools, ...tools];
265+
if (ctx?.API_TOKEN === "flaky" && flakyAttempts++ === 0) {
266+
return [...tools, ...tools];
267+
}
268+
return tools;
269+
},
270+
},
271+
sessionContext: {
272+
enabled: true,
273+
queryParam: {
274+
name: "config",
275+
encoding: "base64",
276+
allowedKeys: ["API_TOKEN"],
277+
},
278+
merge: "shallow",
279+
},
280+
startup: { mode: "STATIC", toolsets: "ALL" },
281+
http: { port },
282+
});
283+
await server.start();
284+
});
285+
286+
afterAll(async () => {
287+
await server.close();
288+
});
289+
290+
const connect = async (clientId: string, token: string) => {
291+
const config = Buffer.from(JSON.stringify({ API_TOKEN: token })).toString("base64");
292+
const transport = new StreamableHTTPClientTransport(
293+
new URL(`http://localhost:${port}/mcp?config=${config}`),
294+
{ requestInit: { headers: { "mcp-client-id": clientId } } }
295+
);
296+
const client = new Client({ name: "test", version: "1.0.0" });
297+
await client.connect(transport);
298+
return client;
299+
};
300+
301+
it("rejects the client instead of connecting with partial tools", async () => {
302+
await expect(connect("failing-preload-client", "bad")).rejects.toThrow(
303+
/Failed to load toolsets/
304+
);
305+
});
306+
307+
it("keeps serving clients whose toolsets load", async () => {
308+
const client = await connect("healthy-preload-client", "good");
309+
expect(extractToolNames(await client.listTools())).toContain("tenant.get_context");
310+
await client.close();
311+
});
312+
313+
it("lets the same client retry after a failed preload", async () => {
314+
await expect(connect("flaky-preload-client", "flaky")).rejects.toThrow(
315+
/Failed to load toolsets/
316+
);
317+
const client = await connect("flaky-preload-client", "flaky");
318+
expect(extractToolNames(await client.listTools())).toContain("tenant.get_context");
319+
await client.close();
320+
});
321+
});
322+
245323
describe("with ALL toolsets", () => {
246324
let server: Awaited<ReturnType<typeof createMcpServer>>;
247325
let port: number;

‎tests/fastifyTransport.test.ts‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { describe, it, expect } from "vitest";
1+
import { describe, it, expect, vi } from "vitest";
22
import Fastify from "fastify";
33
import { FastifyTransport } from "../src/http/FastifyTransport.js";
44
import { DynamicToolManager } from "../src/core/DynamicToolManager.js";
@@ -158,6 +158,62 @@ describe("FastifyTransport", () => {
158158
expect(res3.statusCode).toBe(404);
159159
expect(res3.json().error.message).toContain("not found");
160160

161+
await transport.stop();
162+
});
163+
it("POST /mcp initialize returns a JSON-RPC error when the client's toolsets failed to load", async () => {
164+
const connect = vi.fn(async (_t: any) => {});
165+
const server: any = { connect, close: async () => {} };
166+
const resolver = new ModuleResolver({
167+
catalog: { core: { name: "Core", description: "", tools: [] } } as any,
168+
});
169+
const manager = new DynamicToolManager({ server, resolver });
170+
171+
const app = Fastify({ logger: false });
172+
const createBundle = vi.fn(() => ({
173+
server,
174+
orchestrator: { isReady: async () => false } as any,
175+
}));
176+
const transport = new FastifyTransport(manager, createBundle, {
177+
port: 0,
178+
logger: false,
179+
app,
180+
});
181+
await transport.start();
182+
183+
const initialize = () =>
184+
app.inject({
185+
method: "POST",
186+
url: "/mcp",
187+
headers: {
188+
"mcp-client-id": "failing-client",
189+
"content-type": "application/json",
190+
accept: "application/json, text/event-stream",
191+
},
192+
payload: {
193+
jsonrpc: "2.0",
194+
id: 1,
195+
method: "initialize",
196+
params: {
197+
protocolVersion: "2025-03-26",
198+
capabilities: {},
199+
clientInfo: { name: "test", version: "1.0.0" },
200+
},
201+
},
202+
});
203+
204+
const first = await initialize();
205+
expect(first.statusCode).toBe(500);
206+
expect(first.json()).toEqual({
207+
jsonrpc: "2.0",
208+
error: { code: -32603, message: "Failed to load toolsets for this client." },
209+
id: null,
210+
});
211+
expect(connect).not.toHaveBeenCalled();
212+
213+
// The failed bundle is dropped, so a retry builds a fresh one
214+
expect((await initialize()).statusCode).toBe(500);
215+
expect(createBundle).toHaveBeenCalledTimes(2);
216+
161217
await transport.stop();
162218
});
163219
});

‎tests/serverOrchestrator.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,4 +102,58 @@ describe("ServerOrchestrator", () => {
102102
})
103103
).toThrow(/STATIC mode requires valid toolsets or 'ALL'; none were valid/);
104104
});
105+
it("reports not ready when a startup toolset fails while registering tools", async () => {
106+
const error = vi.spyOn(console, "error").mockImplementation(() => {});
107+
try {
108+
const { server } = createFakeMcpServer();
109+
const clashing = {
110+
core: catalog.core,
111+
other: { name: "Other", description: "", tools: [...catalog.core.tools] },
112+
};
113+
const orch = new ServerOrchestrator({
114+
server,
115+
catalog: clashing as any,
116+
startup: { mode: "STATIC", toolsets: "ALL" },
117+
exposurePolicy: { namespaceToolsWithSetKey: false },
118+
});
119+
expect(await orch.isReady()).toBe(false);
120+
await expect(orch.ensureReady()).rejects.toThrow(
121+
/Failed to enable startup toolsets: .*other.*collision/
122+
);
123+
} finally {
124+
error.mockRestore();
125+
}
126+
});
127+
128+
it("stays ready when the exposure policy refuses a startup toolset", async () => {
129+
const { server } = createFakeMcpServer();
130+
const orch = new ServerOrchestrator({
131+
server,
132+
catalog: catalog as any,
133+
startup: { mode: "STATIC", toolsets: "ALL" },
134+
exposurePolicy: { denylist: ["ext"] },
135+
});
136+
expect(await orch.isReady()).toBe(true);
137+
expect(orch.getManager().getActiveToolsets()).toEqual(["core"]);
138+
});
139+
140+
it("stays ready when startup.toolsets lists a toolset twice", async () => {
141+
const { server } = createFakeMcpServer();
142+
const orch = new ServerOrchestrator({
143+
server,
144+
catalog: catalog as any,
145+
startup: { mode: "STATIC", toolsets: ["core", "core"] },
146+
});
147+
expect(await orch.isReady()).toBe(true);
148+
});
149+
150+
it("reports ready when every startup toolset enables", async () => {
151+
const { server } = createFakeMcpServer();
152+
const orch = new ServerOrchestrator({
153+
server,
154+
catalog: catalog as any,
155+
startup: { mode: "STATIC", toolsets: "ALL" },
156+
});
157+
expect(await orch.isReady()).toBe(true);
158+
});
105159
});

0 commit comments

Comments
 (0)