Files

77 lines
2.3 KiB
TypeScript

const ACCEPT = "application/json, text/event-stream";
interface JsonRpcResponse {
result?: unknown;
error?: { code: number; message: string };
}
interface McpTool {
name: string;
description?: string;
inputSchema?: unknown;
}
type McpContentBlock = { type: string; text: string } | { type: string; [key: string]: unknown };
interface McpToolResult {
content?: McpContentBlock[];
}
function parseMcpResponse(text: string): JsonRpcResponse {
const trimmed = text.trim();
if (!trimmed) throw new Error("Empty MCP response");
if (trimmed.startsWith("{")) {
return JSON.parse(trimmed) as JsonRpcResponse;
}
if (trimmed.includes("event:") || trimmed.includes("data:")) {
let payload = "";
for (const line of trimmed.split(/\r?\n/)) {
if (line.startsWith("data:")) payload += line.slice(5).trim();
}
if (payload.startsWith("{")) return JSON.parse(payload) as JsonRpcResponse;
}
throw new Error(`Unrecognized MCP response format: ${trimmed.slice(0, 200)}`);
}
export class McpClient {
private url: string;
private seq: number;
constructor(url: string) {
this.url = url;
this.seq = 0;
}
async request(method: string, params: Record<string, unknown> = {}): Promise<JsonRpcResponse> {
this.seq += 1;
const res = await fetch(this.url, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: ACCEPT },
body: JSON.stringify({ jsonrpc: "2.0", id: this.seq, method, params }),
});
if (!res.ok) {
throw new Error(`MCP HTTP ${res.status}: ${(await res.text()).slice(0, 300)}`);
}
const rpc = parseMcpResponse(await res.text());
if (rpc.error) throw new Error(`MCP RPC error ${rpc.error.code}: ${rpc.error.message}`);
return rpc;
}
async listTools(): Promise<McpTool[]> {
const rpc = await this.request("tools/list");
return (rpc.result as { tools?: McpTool[] })?.tools ?? [];
}
async callTool(name: string, args: Record<string, unknown> = {}): Promise<McpToolResult> {
const rpc = await this.request("tools/call", { name, arguments: args });
return rpc.result as McpToolResult;
}
}
export function textContentFrom(result: McpToolResult | null | undefined): string {
if (!result?.content) return "";
return result.content
.map((b) => (b.type === "text" ? b.text : JSON.stringify(b)))
.join(" ");
}