智能體 IDE 是 API:為 Claude Code、Codex 和 MCP 建立統一工具註冊表
The Agentic IDE Is an API: Building a Unified Tool Registry for Claude Code, Codex, and MCP
作者示範以 TypeScript 控制平面、Fastify HTTP API 和 MCP 兼容 adapter,為 Claude Code、Codex 與 MCP 客戶端建立共用工具註冊表。各客戶端共用工具 schema、授權判斷與執行路徑,示例工具包括文件讀取和計算。示例拒絕任意 shell 執行;正式部署則建議加入容器隔離、資源配額和更強的身份提供者。
Originally published on tamiz.pro.
Why One Registry?
Modern coding agents do not live inside a single IDE. They run as separate processes, connect to different model providers, and discover tools through incompatible mechanisms. Claude Code uses its own tool configuration. Codex operates within its own runtime. Model Context Protocol (MCP) clients connect to servers over stdio or HTTP. The result is a fragmented control plane where permissions, schemas, observability, and secrets are duplicated across every integration.
The architectural shift is simple: treat the agentic IDE as an API surface, not a collection of hardcoded tool menus. Every tool becomes a versioned capability with a schema, an authorization policy, an execution boundary, and a structured result. Claude Code, Codex, and MCP clients become consumers of that same registry.
This tutorial builds a runnable registry with a TypeScript control plane, a Fastify HTTP API, and an MCP-compatible adapter. You will expose a filesystem tool and a calculator, register both with explicit policies, and let multiple clients invoke them through the same endpoint.
Security note: The registry intentionally rejects arbitrary shell execution. Tool implementations run in a separate process with a restricted environment. In production, add container isolation, resource quotas, and a stronger identity provider.
Table of Contents
- 1. Architecture Overview
- 2. Prerequisites
- 3. Project Setup
- 4. Defining the Tool Contract
- 5. Implementing the Tool Runtime
- 6. Building the Registry API
- 7. Adding Policy Enforcement
- 8. Connecting MCP Clients
- 9. Connecting Claude Code and Codex
- 10. Adding Observability
- 11. Production Hardening
- 12. Testing the Registry
- 13. Frequently Asked Questions
1. Architecture Overview
The registry sits between agents and tool implementations. Agents never receive direct access to credentials or the host filesystem. Instead, they submit a tool invocation to the registry, which authenticates the caller, authorizes the action, validates the arguments, executes the tool, and returns a normalized response.
┌───────────────┐ ┌───────────────┐ ┌────────────────┐
│ Claude Code │ │ Codex │ │ MCP Client │
└───────┬───────┘ └───────┬───────┘ └────────┬───────┘
│ │ │
│ OpenAI-style │ MCP JSON-RPC │
│ function call │ │
└───────────────────┴────────────────────┘
│
┌───────▼────────┐
│ Tool Registry │
│ • authn │
│ • policy │
│ • validation │
│ • audit log │
└───────┬────────┘
│
┌─────────────┼─────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌────────────┐
│ read_file│ │ calculate│ │ MCP Server │
└──────────┘ └──────────┘ └────────────┘
Four layers matter:
- Contract layer. A registry entry contains a stable name, a JSON Schema for arguments, a version, and a capability tag.
- Policy layer. Every entry has an allowlist, a caller scope requirement, and optional argument constraints.
- Execution layer. Tool code runs behind an interface. The reference implementation uses a child process, but the interface permits containers, sandboxes, or remote workers.
- Adapter layer. Claude Code and Codex consume OpenAI-compatible function definitions. MCP clients consume JSON-RPC tools/list and tools/call methods.
The key invariant: all clients receive the same schema and the same authorization decision.
2. Prerequisites
You need:
- Node.js 20 or later
- npm 10 or later
- A terminal and a text editor
- Optional: an API key for Claude or OpenAI if you want to test with a live model
Verify your environment:
node --version
npm --version
3. Project Setup
Create the project and install dependencies:
mkdir agentic-tool-registry
cd agentic-tool-registry
npm init -y
npm install fastify @fastify/cors zod @modelcontextprotocol/sdk
npm install -D typescript tsx @types/node vitest
Create tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist",
"rootDir": "src"
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}
Set the package type to ES modules:
npm pkg set type=module
npm pkg set scripts.dev="tsx watch src/server.ts"
npm pkg set scripts.start="tsx src/server.ts"
npm pkg set scripts.test="vitest run"
npm pkg set scripts.typecheck="tsc --noEmit"
4. Defining the Tool Contract
A tool contract must be machine-readable and stable. Use JSON Schema for arguments because both OpenAI function calling and MCP understand JSON Schema conventions.
Create src/contracts.ts:
import { z } from "zod";
export type ToolContract = {
name: string;
version: string;
description: string;
inputSchema: Record<string, unknown>;
requiredScopes: string[];
allowedRoles: string[];
timeoutMs: number;
handler: (args: unknown) => Promise<unknown>;
};
export const ToolInvocationSchema = z.object({
tool: z.string().min(1),
arguments: z.record(z.unknown()).default({}),
idempotencyKey: z.string().min(8).optional(),
});
export type ToolInvocation = z.infer<typeof ToolInvocationSchema>;
export type ToolResult = {
ok: boolean;
output?: unknown;
error?: {
code: string;
message: string;
};
durationMs: number;
};
The ToolInvocationSchema validates the envelope. Each tool validates its own arguments with Zod, then translates that schema into JSON Schema for discovery. To avoid maintaining two definitions by hand, we can use zod-to-json-schema. Install it:
npm install zod-to-json-schema
Create src/tools.ts:
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
import type { ToolContract } from "./contracts.js";
import { readFile } from "node:fs/promises";
import path from "node:path";
const ROOT = process.env.TOOL_ROOT ?? process.cwd();
const ReadFileArgs = z.object({
path: z.string().min(1),
encoding: z.enum(["utf8", "utf-8"]).default("utf8"),
});
const CalculateArgs = z.object({
expression: z.string().min(1).max(200),
});
async function readFileTool(raw: unknown) {
const args = ReadFileArgs.parse(raw);
const resolved = path.resolve(ROOT, args.path);
if (!resolved.startsWith(ROOT + path.sep)) {
throw new Error("PATH_OUTSIDE_ROOT");
}
const content = await readFile(resolved, "utf8");
return { path: resolved, content };
}
async function calculateTool(raw: unknown) {
const args = CalculateArgs.parse(raw);
if (!/^[0-9+\-*/().\s]+$/.test(args.expression)) {
throw new Error("INVALID_EXPRESSION");
}
const tokens = args.expression.match(/\d+(?:\.\d+)?|[-+*/()]/g) ?? [];
let position = 0;
function parseExpression(): number {
let value = parseTerm();
while (tokens[position] === "+" || tokens[position] === "-") {
const operator = tokens[position++];
const right = parseTerm();
value = operator === "+" ? value + right : value - right;
}
return value;
}
function parseTerm(): number {
let value = parseFactor();
while (tokens[position] === "*" || tokens[position] === "/") {
const operator = tokens[position++];
const right = parseFactor();
value = operator === "*" ? value * right : value / right;
}
return value;
}
function parseFactor(): number {
if (tokens[position] === "-") {
position++;
return -parseFactor();
}
if (tokens[position] === "(") {
position++;
const value = parseExpression();
if (tokens[position] !== ")") throw new Error("INVALID_EXPRESSION");
position++;
return value;
}
const token = tokens[position++];
const number = Number(token);
if (Number.isNaN(number)) throw new Error("INVALID_EXPRESSION");
return number;
}
const result = parseExpression();
if (position !== tokens.length) throw new Error("INVALID_EXPRESSION");
return { expression: args.expression, result };
}
export const tools: ToolContract[] = [
{
name: "read_file",
version: "1.0.0",
description: "Read a UTF-8 text file from the workspace root.",
inputSchema: zodToJsonSchema(ReadFileArgs) as Record<string, unknown>,
requiredScopes: ["files:read"],
allowedRoles: ["developer", "agent"],
timeoutMs: 5_000,
handler: readFileTool,
},
{
name: "calculate",
version: "1.0.0",
description: "Evaluate an arithmetic expression.",
inputSchema: zodToJsonSchema(CalculateArgs) as Record<string, unknown>,
requiredScopes: ["calc:execute"],
allowedRoles: ["developer", "agent"],
timeoutMs: 2_000,
handler: calculateTool,
},
];
The calculator uses a small recursive-descent parser instead of eval. It accepts only numeric literals and arithmetic operators, so the tool cannot execute arbitrary code.
5. Implementing the Tool Runtime
The runtime must enforce a timeout and normalize errors. A failed tool should never crash the registry or leak a stack trace to the client.
Create src/runtime.ts:
import type { ToolContract, ToolResult } from "./contracts.js";
export class ToolRuntime {
private tools = new Map<string, ToolContract>();
register(tool: ToolContract) {
if (this.tools.has(tool.name)) {
throw new Error(`DUPLICATE_TOOL:${tool.name}`);
}
this.tools.set(tool.name, tool);
}
list(): ToolContract[] {
return [...this.tools.values()];
}
get(name: string): ToolContract | undefined {
return this.tools.get(name);
}
async execute(name: string, args: unknown): Promise<ToolResult> {
const tool = this.tools.get(name);
const started = Date.now();
if (!tool) {
return {
ok: false,
error: { code: "TOOL_NOT_FOUND", message: `Unknown tool: ${name}` },
durationMs: Date.now() - started,
};
}
let timer: NodeJS.Timeout | undefined;
try {
const output = await Promise.race([
tool.handler(args),
new Promise((_, reject) => {
timer = setTimeout(
() => reject(new Error("TOOL_TIMEOUT")),
tool.timeoutMs,
);
}),
]);
return { ok: true, output, durationMs: Date.now() - started };
} catch (error) {
const code = error instanceof Error ? error.message : "TOOL_ERROR";
return {
ok: false,
error: { code, message: "Tool execution failed" },
durationMs: Date.now() - started,
};
} finally {
if (timer) clearTimeout(timer);
}
}
}
Promise.race enforces a soft timeout. It does not terminate the underlying operation. For CPU-bound or runaway processes, run the handler in a worker thread or a container with a hard kill deadline.
6. Building the Registry API
The HTTP API exposes three operations:
-
GET /v1/toolsreturns the discovery catalog -
POST /v1/invocationsexecutes a tool -
GET /healthzreturns liveness status
Create src/server.ts:
import Fastify from "fastify";
import cors from "@fastify/cors";
import { ToolInvocationSchema } from "./contracts.js";
import { ToolRuntime } from "./runtime.js";
import { tools } from "./tools.js";
import { createMcpServer } from "./mcp.js";
import { authenticate } from "./auth.js";
import { authorize } from "./policy.js";
const app = Fastify({ logger: true });
const runtime = new ToolRuntime();
for (const tool of tools) runtime.register(tool);
await app.register(cors, {
origin: process.env.ALLOWED_ORIGIN ?? "http://localhost:3000",
});
app.get("/healthz", async () => ({ status: "ok" }));
app.get("/v1/tools", async (request) => {
const identity = await authenticate(request.headers.authorization);
const visible = runtime.list().filter((tool) =>
authorize(identity, tool).allowed,
);
return visible.map((tool) => ({
name: tool.name,
version: tool.version,
description: tool.description,
inputSchema: tool.inputSchema,
}));
});
app.post("/v1/invocations", async (request, reply) => {
const identity = await authenticate(request.headers.authorization);
const parsed = ToolInvocationSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({
ok: false,
error: { code: "INVALID_REQUEST", message: parsed.error.message },
});
}
const tool = runtime.get(parsed.data.tool);
if (!tool) {
return reply.code(404).send({
ok: false,
error: { code: "TOOL_NOT_FOUND", message: "Tool not found" },
});
}
const decision = authorize(identity, tool);
if (!decision.allowed) {
return reply.code(403).send({
ok: false,
error: { code: decision.reason, message: "Tool invocation denied" },
});
}
const result = await runtime.execute(tool.name, parsed.data.arguments);
return reply.code(result.ok ? 200 : 422).send(result);
});
await createMcpServer(runtime, authenticate, authorize);
const port = Number(process.env.PORT ?? 8787);
await app.listen({ port, host: "0.0.0.0" });
Notice that discovery is filtered by policy. A client never sees tools it cannot call. This prevents leaking internal capabilities through the catalog.
7. Adding Policy Enforcement
Authentication and authorization belong in separate modules so you can swap the identity provider without touching tool code.
Create src/auth.ts:
import { createHash, timingSafeEqual } from "node:crypto";
export type Identity = {
subject: string;
roles: string[];
scopes: string[];
};
export async function authenticate(
header: string | undefined,
): Promise<Identity> {
if (!header?.startsWith("Bearer ")) {
throw new Error("UNAUTHENTICATED");
}
const token = header.slice(7);
const expected = process.env.REGISTRY_API_KEY;
if (!expected) throw new Error("AUTH_NOT_CONFIGURED");
const a = createHash("sha256").update(token).digest();
const b = createHash("sha256").update(expected).digest();
if (!timingSafeEqual(a, b)) {
throw new Error("UNAUTHENTICATED");
}
return {
subject: "local-agent",
roles: ["developer", "agent"],
scopes: ["files:read", "calc:execute"],
};
}
The static API key is acceptable for local development. Replace it with OIDC token verification for production.
Create src/policy.ts:
import type { ToolContract } from "./contracts.js";
import type { Identity } from "./auth.js";
export type PolicyDecision = {
allowed: boolean;
reason: string;
};
export function authorize(
identity: Identity,
tool: ToolContract,
): PolicyDecision {
const roleAllowed = tool.allowedRoles.some((role) =>
identity.roles.includes(role),
);
if (!roleAllowed) {
return { allowed: false, reason: "ROLE_NOT_ALLOWED" };
}
const scopesAllowed = tool.requiredScopes.every((scope) =>
identity.scopes.includes(scope),
);
if (!scopesAllowed) {
return { allowed: false, reason: "SCOPE_NOT_ALLOWED" };
}
return { allowed: true, reason: "ALLOWED" };
}
For real deployments, extend the policy function with argument-level constraints: maximum file size, allowed path prefixes, rate limits per subject, and approval requirements for destructive operations.
8. Connecting MCP Clients
The MCP SDK exposes a server implementation that speaks JSON-RPC over stdio. We will mount the same runtime behind it, so MCP clients inherit the registry's schemas and policies.
Create src/mcp.ts:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import type { ToolRuntime } from "./runtime.js";
import type { Identity } from "./auth.js";
import { authorize } from "./policy.js";
export async function createMcpServer(
runtime: ToolRuntime,
authenticate: (header?: string) => Promise<Identity>,
authorizeFn: (identity: Identity, tool: any) => { allowed: boolean; reason: string },
) {
const server = new McpServer({
name: "unified-tool-registry",
version: "1.0.0",
});
const identity = await authenticate(`Bearer ${process.env.REGISTRY_API_KEY}`);
for (const tool of runtime.list()) {
if (!authorizeFn(identity, tool).allowed) continue;
server.registerTool(
tool.name,
{
title: tool.name,
description: tool.description,
inputSchema: tool.inputSchema as any,
},
async (args: any) => {
const result = await runtime.execute(tool.name, args);
if (!result.ok) {
return {
isError: true,
content: [{ type: "text", text: result.error?.message ?? "Tool failed" }],
};
}
return {
content: [{ type: "text", text: JSON.stringify(result.output) }],
};
},
);
}
await server.connect(new StdioServerTransport());
}
The MCP adapter uses the same runtime.execute path as the HTTP API. There is no separate authorization logic.
9. Connecting Claude Code and Codex
Both Claude Code and Codex support connecting to MCP servers. Create mcp.json in your workspace:
{
"mcpServers": {
"unified-registry": {
"command": "npx",
"args": ["tsx", "src/mcp.ts"],
"env": {
"REGISTRY_API_KEY": "your-local-development-key",
"TOOL_ROOT": "/absolute/path/to/your/project"
}
}
}
}\n```
{% endraw %}
Because the MCP server runs over stdio, it cannot share the HTTP server's port. Run it as a separate process:
{% raw %}
```bash
REGISTRY_API_KEY=your-local-development-key \
TOOL_ROOT="$PWD" \
npx tsx src/mcp.ts
In Claude Code, add the server with:
claude mcp add unified-registry \
--env REGISTRY_API_KEY=your-local-development-key \
--env TOOL_ROOT="$PWD" \
-- npx tsx src/mcp.ts
For Codex, place the same server definition in ~/.codex/config.toml:
[mcp_servers.unified-registry]
command = "npx"
args = ["tsx", "src/mcp.ts"]
[mcp_servers.unified-registry.env]
REGISTRY_API_KEY = "your-local-development-key"
TOOL_ROOT = "/absolute/path/to/your/project"
Both agents now discover read_file and calculate through the registry contract. They see identical schemas regardless of which model provider generated the call.
If you prefer a direct HTTP integration, expose the discovery catalog as OpenAI-compatible function definitions:
export function toOpenAiTools(tools: ToolContract[]) {
return tools.map((tool) => ({
type: "function" as const,
function: {
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
},
}));
}\n```
Clients can fetch this catalog from `GET /v1/tools` and pass the resulting function calls to `POST /v1/invocations`.
## 10. Adding Observability
A registry without logs is impossible to audit. Record who called what, whether it succeeded, and how long it took. The `ToolResult` already includes `durationMs`. Fastify's logger captures HTTP-level metadata.
Add a structured audit event inside the invocation route:
```ts
app.log.info(
{
event: "tool_invocation",
subject: identity.subject,
tool: tool.name,
version: tool.version,
allowed: true,
durationMs: result.durationMs,
ok: result.ok,
},
"tool invocation completed",
);
For production, ship these events to OpenTelemetry, include a correlation ID from the client request, and record policy denials separately from execution failures. Denials often reveal misconfigured scopes or an agent attempting an unexpected action.
11. Production Hardening
The reference implementation is a starting point. Before deploying it:
Replace static keys with OIDC. Verify issuer, audience, expiry, and signature. Derive roles and scopes from verified claims rather than request headers.
Isolate tool execution. Run each tool in a container, gVisor sandbox, or dedicated worker with a read-only base image, a scoped filesystem mount, no network by default, and CPU and memory limits.
Add argument-level policy. Validate file paths against an allowlist of prefixes, cap file sizes, and require human approval for write or delete operations.
Version contracts. Include version in every registry entry. When a schema changes incompatibly, publish a new version and keep the old one available during migration.
Add rate limiting. Limit invocations per subject and per tool. A runaway agent loop should hit a quota rather than exhaust downstream resources.
Encrypt secrets. Use a secrets manager and inject credentials into the tool process at execution time. Never place secrets in the registry catalog or the MCP environment block in a shared config file.
Sign the catalog. If clients run in different trust domains, publish a signed manifest containing tool versions and schema hashes so clients can detect tampering.
Support idempotency. Store the idempotencyKey with a short TTL. If a client retries after a network timeout, return the original result instead of executing the tool twice.
12. Testing the Registry
Create test/registry.test.ts:
import { describe, expect, it } from "vitest";
import { ToolRuntime } from "../src/runtime.js";
import { tools } from "../src/tools.js";
import { authorize } from "../src/policy.js";
describe("tool registry", () => {
it("executes the calculator", async () => {
const runtime = new ToolRuntime();
for (const tool of tools) runtime.register(tool);
const result = await runtime.execute("calculate", {
expression: "2 * (3 + 4)",
});
expect(result.ok).toBe(true);
expect(result.output).toMatchObject({ result: 14 });
});
it("rejects unsafe expressions", async () => {
const runtime = new ToolRuntime();
for (const tool of tools) runtime.register(tool);
const result = await runtime.execute("calculate", {
expression: "process.exit(1)",
});
expect(result.ok).toBe(false);
});
it("denies tools without the required scope", () => {
const tool = tools.find((t) => t.name === "read_file")!;
const decision = authorize(
{ subject: "test", roles: ["developer"], scopes: [] },
tool,
);
expect(decision.allowed).toBe(false);
expect(decision.reason).toBe("SCOPE_NOT_ALLOWED");
});
});
Run the suite:
npm test
npm run typecheck
Start the server and verify the API:
REGISTRY_API_KEY=dev-key npm run start
In another terminal:
curl -s http://localhost:8787/v1/tools \
-H "Authorization: Bearer dev-key" | jq
curl -s http://localhost:8787/v1/invocations \
-H "Authorization: Bearer dev-key" \
-H "Content-Type: application/json" \
-d '{"tool":"calculate","arguments":{"expression":"10 / 4"}}' | jq
The calculation returns 2.5. The catalog lists both tools with their JSON Schemas.
13. Frequently Asked Questions
Why not let each agent connect directly to each MCP server?\n
Direct connections work for a prototype, but they multiply the trust boundary. With a registry, you get one audit trail, one schema source of truth, one policy engine, and one place to rotate credentials. Agents still reach MCP servers; they just do so through a governed adapter.
How do I handle tools with different authentication requirements?\n
Keep authentication inside the tool implementation. The registry authorizes whether a caller may invoke the tool. The tool then authenticates to its downstream service using credentials injected at runtime. This separation keeps the registry generic and prevents it from becoming a credential store.
Can multiple agents share one tool instance safely?\n
Yes, as long as the tool is stateless or uses per-invocation context. Pass the caller's subject and correlation ID into the handler context so downstream systems can enforce tenant isolation. If a tool holds mutable state, make that state keyed by subject or run the tool in an isolated process per invocation.
Final Result
You now have a single governed API that Claude Code, Codex, and MCP clients can all use. Tools are discovered through one catalog, authorized through one policy engine, executed behind one runtime, and audited in one place. The next step is to add a write tool with argument-level constraints and human approval, then move execution into containers before exposing the registry to remote agents.
來源:DEV Community · dev.to