Add JSON validation to MCP tool responses

This commit is contained in:
Mohamed Boudra
2025-11-15 18:18:14 +01:00
parent 2a02f41182
commit e7b8cc373c
4 changed files with 103 additions and 28 deletions
+24 -22
View File
@@ -2,6 +2,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { homedir } from "node:os";
import { resolve } from "node:path";
import { ensureValidJson } from "../json-utils.js";
import type {
AgentPromptInput,
AgentProvider,
@@ -294,14 +295,14 @@ export async function createAgentMcpServer(
return {
content: [],
structuredContent: {
structuredContent: ensureValidJson({
agentId: snapshot.id,
type: provider,
status: snapshot.status,
cwd: snapshot.cwd,
currentModeId: snapshot.currentModeId,
availableModes: snapshot.availableModes,
},
}),
};
}
);
@@ -333,12 +334,12 @@ export async function createAgentMcpServer(
return {
content: [],
structuredContent: {
structuredContent: ensureValidJson({
agentId,
status: result.status,
permission: result.permission,
activity,
},
}),
};
}
);
@@ -372,10 +373,10 @@ export async function createAgentMcpServer(
return {
content: [],
structuredContent: {
structuredContent: ensureValidJson({
success: true,
status: snapshot?.status ?? "idle",
},
}),
};
}
);
@@ -400,15 +401,16 @@ export async function createAgentMcpServer(
throw new Error(`Agent ${agentId} not found`);
}
const structuredSnapshot = await serializeSnapshotWithMetadata(
agentRegistry,
snapshot
);
return {
content: [],
structuredContent: {
structuredContent: ensureValidJson({
status: snapshot.status,
snapshot: await serializeSnapshotWithMetadata(
agentRegistry,
snapshot
),
},
snapshot: structuredSnapshot,
}),
};
}
);
@@ -432,7 +434,7 @@ export async function createAgentMcpServer(
);
return {
content: [],
structuredContent: { agents },
structuredContent: ensureValidJson({ agents }),
};
}
);
@@ -454,7 +456,7 @@ export async function createAgentMcpServer(
const success = await agentManager.cancelAgentRun(agentId);
return {
content: [],
structuredContent: { success },
structuredContent: ensureValidJson({ success }),
};
}
);
@@ -475,7 +477,7 @@ export async function createAgentMcpServer(
await agentManager.closeAgent(agentId);
return {
content: [],
structuredContent: { success: true },
structuredContent: ensureValidJson({ success: true }),
};
}
);
@@ -513,14 +515,14 @@ export async function createAgentMcpServer(
if (format === "curated") {
return {
content: [],
structuredContent: {
structuredContent: ensureValidJson({
agentId,
format: "curated" as const,
updateCount: timeline.length,
currentModeId: snapshot?.currentModeId ?? null,
content: curateAgentActivity(timeline),
updates: null,
},
}),
};
}
@@ -529,14 +531,14 @@ export async function createAgentMcpServer(
: timeline;
return {
content: [],
structuredContent: {
structuredContent: ensureValidJson({
agentId,
format: "raw" as const,
updateCount: timeline.length,
currentModeId: snapshot?.currentModeId ?? null,
content: "",
updates: entries,
},
}),
};
}
);
@@ -560,7 +562,7 @@ export async function createAgentMcpServer(
await agentManager.setAgentMode(agentId, modeId);
return {
content: [],
structuredContent: { success: true, newMode: modeId },
structuredContent: ensureValidJson({ success: true, newMode: modeId }),
};
}
);
@@ -593,7 +595,7 @@ export async function createAgentMcpServer(
return {
content: [],
structuredContent: { permissions },
structuredContent: ensureValidJson({ permissions }),
};
}
);
@@ -617,7 +619,7 @@ export async function createAgentMcpServer(
await agentManager.respondToPermission(agentId, requestId, response);
return {
content: [],
structuredContent: { success: true },
structuredContent: ensureValidJson({ success: true }),
};
}
);
+60
View File
@@ -0,0 +1,60 @@
export type JsonValue =
| string
| number
| boolean
| null
| JsonValue[]
| { [key: string]: JsonValue };
/**
* Ensure the provided value only contains JSON-safe primitives.
* Throws when undefined, functions, symbols, BigInts, etc. are found.
*/
export function ensureValidJson<T>(value: T, rootLabel: string = "root"): T {
const seen = new Set<object>();
const validate = (current: unknown, path: string): void => {
if (current === undefined) {
throw new Error(`Invalid JSON value at ${path}: undefined`);
}
if (current === null) {
return;
}
const type = typeof current;
if (type === "string" || type === "number" || type === "boolean") {
return;
}
if (Array.isArray(current)) {
current.forEach((item, index) =>
validate(item, `${path}[${index}]`)
);
return;
}
if (type === "object") {
const asObject = current as Record<string, unknown>;
if (!seen.has(asObject)) {
seen.add(asObject);
for (const [key, val] of Object.entries(asObject)) {
const nextPath = path === rootLabel ? key : `${path}.${key}`;
validate(val, nextPath);
}
seen.delete(asObject);
}
return;
}
throw new Error(
`Invalid JSON value at ${path}: ${
type === "symbol" ? "symbol" : String(current)
}`
);
};
validate(value, rootLabel);
return value;
}
@@ -1,5 +1,6 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { ensureValidJson } from "../json-utils.js";
import { TerminalManager } from "./terminal-manager.js";
export interface TerminalMcpServerOptions {
@@ -98,7 +99,7 @@ export async function createTerminalMcpServer(
const output = { commands };
return {
content: [],
structuredContent: output,
structuredContent: ensureValidJson(output),
};
}
);
@@ -131,7 +132,7 @@ export async function createTerminalMcpServer(
const result = await terminalManager.captureCommand(commandId, lines);
return {
content: [],
structuredContent: result,
structuredContent: ensureValidJson(result),
};
}
);
@@ -190,7 +191,7 @@ export async function createTerminalMcpServer(
const result = { output: output || null };
return {
content: [],
structuredContent: result,
structuredContent: ensureValidJson(result),
};
}
);
@@ -238,7 +239,7 @@ export async function createTerminalMcpServer(
const result = { output: output || null };
return {
content: [],
structuredContent: result,
structuredContent: ensureValidJson(result),
};
}
);
@@ -272,7 +273,7 @@ export async function createTerminalMcpServer(
const output = { success: true, killedCount };
return {
content: [],
structuredContent: output,
structuredContent: ensureValidJson(output),
};
}
);