ai newsMi., 25. Nov.
EilmeldungYale’s Sonnenfeld: Nvidia is a ‘detriment’ to U.S. industrial might — not a champion

Agenten-IDE als API: Einheitliche Tool-Registry fuer Claude Code, Codex und MCP

Moderne Coding-Agenten laufen als eigene Prozesse, nutzen unterschiedliche Modelle und finden Tools ueber inkompatible Mechanismen. Ein einheitliches Registry soll Claude Code und Codex unter einem Dach verbinden.

dev.toDienstag 01:02 · 24.11.DE16 Min. Lesezeit
Bild: dev.to

Veröffentlicht am 24. Nov • Original veröffentlicht auf tamiz.pro

Moderne Coding-Agents leben nicht mehr in einer einzigen IDE. Sie laufen als eigenständige Prozesse, verbinden sich mit verschiedenen Modell-Anbietern und entdecken Tools über inkompatible Mechanismen. Claude Code verwendet eine eigene Tool-Konfiguration. Codex operiert innerhalb seiner eigenen Runtime. Model Context Protocol (MCP)-Clients verbinden sich über stdio oder HTTP mit Servern. Das Ergebnis ist eine fragmentierte Control Plane, in der Berechtigungen, Schemas, Observability und Secrets über jede Integration hinweg dupliziert werden.

Der architektonische Wandel ist einfach: Betrachten Sie die agentische IDE als API-Oberfläche, nicht als eine Sammlung hartcodierter Tool-Menüs. Jedes Tool wird zu einer versionierten Capability mit einem Schema, einer Autorisierungsrichtlinie, einer Ausführungsgrenze und einem strukturierten Ergebnis. Claude Code, Codex und MCP-Clients werden zu Konsumenten derselben Registry.

Dieses Tutorial baut eine lauffähige Registry mit einer TypeScript-Control-Plane, einer Fastify-HTTP-API und einem MCP-kompatiblen Adapter. Sie werden ein Dateisystem-Tool und einen Taschenrechner expose, beide mit expliziten Richtlinien registrieren und mehrere Clients dieselben über denselben Endpunkt aufrufen lassen.

Sicherheitshinweis: Die Registry leitet beliebige Shell-Ausführung bewusst ab. Tool-Implementierungen laufen in einem separaten Prozess mit eingeschränkter Umgebung. Ergänzen Sie in Produktion Container-Isolation, Ressourcen-Quotas und einen stärkeren Identity Provider.

Die Registry liegt zwischen den Agents und den Tool-Implementierungen. Agents erhalten niemals direkten Zugriff auf Credentials oder das Host-Dateisystem. Stattdessen übermitteln sie einen Tool-Aufruf an die Registry, welche den Aufrufer authentifiziert, die Aktion autorisiert, die Argumente validiert, das Tool ausführt und eine normalisierte Antwort zurückgibt.

┌───────────────┐ ┌───────────────┐ ┌────────────────┐ │ Claude Code │ │ Codex │ │ MCP Client │ └───────┬───────┘ └───────┬───────┘ └────────┬───────┘ │ │ │ │ OpenAI-style │ MCP JSON-RPC │ │ function call │ │ └───────────────────┴────────────────────┘ │ ┌───────▼────────┐ │ Tool Registry │ │ • authn │ │ • policy │ │ • validation │ │ • audit log │ └───────┬────────┘ │ ┌─────────────┼─────────────┐ ▼ ▼ ▼ ┌──────────┐ ┌──────────┐ ┌────────────┐ │ read_file│ │ calculate│ │ MCP Server │ └──────────┘ └──────────┘ └────────────┘ Vollbildmodus öffnen Vollbildmodus verlassen Vier Schichten sind entscheidend:

Die zentrale Invariante: Alle Clients erhalten dasselbe Schema und dieselbe Autorisierungsentscheidung.

node --version npm --version Vollbildmodus öffnen Vollbildmodus verlassen 3. Projekt-Setup Erstellen Sie das Projekt und installieren Sie die Abhängigkeiten:

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 Vollbildmodus öffnen Vollbildmodus verlassen Erstellen Sie tsconfig.json:

{ "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "outDir": "dist", "rootDir": "src" }, "include": [ "src/**/*.ts", "test/**/*.ts" ] } Vollbildmodus öffnen Vollbildmodus verlassen Setzen Sie den Package-Typ auf 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" Vollbildmodus öffnen Vollbildmodus verlassen 4. Definieren des Tool-Contracts Ein Tool-Contract muss maschinenlesbar und stabil sein. Verwenden Sie JSON Schema für Argumente, da sowohl OpenAI function calling als auch MCP die JSON-Schema-Konventionen verstehen.

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; }; Vollbildmodus öffnen Vollbildmodus verlassen Das ToolInvocationSchema validiert den Envelope. Jedes Tool validiert seine eigenen Argumente mit Zod und übersetzt dieses Schema anschließend in JSON Schema für die Discovery. Um nicht zwei Definitionen von Hand pflegen zu müssen, können wir zod-to-json-schema verwenden.

Installieren Sie es:

npm install zod-to-json-schema Vollbildmodus öffnen Vollbildmodus verlassen Erstellen Sie 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, }, ]; Vollbildmodus öffnen Vollbildmodus verlassen Der Taschenrechner verwendet einen kleinen Recursive-Descent-Parser statt eval. Er akzeptiert nur numerische Literale und arithmetische Operatoren, sodass das Tool keinen beliebigen Code ausführen kann.

Die Runtime muss einen Timeout durchsetzen und Fehler normalisieren. Ein fehlgeschlagenes Tool sollte die Registry niemals zum Absturz bringen oder einen Stack Trace an den Client weitergeben.

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); } } } Vollbildmodus aufrufen Vollbildmodus verlassen Promise.race erzwingt ein Soft-Timeout. Es beendet nicht die zugrunde liegende Operation.

Für CPU-gebundene oder außer Kontrolle geratene Prozesse sollte der Handler in einem Worker-Thread oder in einem Container mit einer harten Kill-Frist ausgeführt werden.

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" }); Vollbildmodus aufrufen Vollbildmodus verlassen Beachten Sie, dass die Entdeckung (Discovery) durch die Policy gefiltert wird.

Ein Client sieht niemals Tools, die er nicht aufrufen kann. Dadurch wird verhindert, dass interne Fähigkeiten über den Katalog geleakt werden.

Authentifizierung und Autorisierung gehören in separate Module, damit Sie den Identity Provider austauschen können, ohne den Tool-Code anzufassen.

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"] }; } Vollbildmodus aufrufen Vollbildmodus verlassen Der statische API-Schlüssel ist für die lokale Entwicklung akzeptabel. Ersetzen Sie ihn für die Produktion durch eine OIDC-Token-Verifizierung.

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" }; } Vollbildmodus aufrufen Vollbildmodus verlassen Für echte Deployments sollten Sie die Policy-Funktion um Einschränkungen auf Argumentebene erweitern: maximale Dateigröße, erlaubte Pfad-Präfixe, Rate-Limits pro Subject und Freigabepflichten für destruktive Operationen.

Das MCP SDK stellt eine Server-Implementierung bereit, die JSON-RPC über stdio spricht. Wir werden dieselbe Runtime dahinter mounten, sodass MCP-Clients die Schemas und Policies der Registry erben.

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()); } Vollbildmodus aufrufen Vollbildmodus verlassen Der MCP-Adapter verwendet denselben Pfad runtime.execute wie die HTTP-API. Es gibt keine separate Autorisierungslogik.

Sowohl Claude Code als auch Codex unterstützen die Verbindung zu MCP-Servern. Erstellen Sie mcp.json in Ihrem 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 % } Da der MCP-Server über stdio läuft, kann er den Port des HTTP-Servers nicht mitverwenden. Führen Sie ihn als separaten Prozess aus: { % raw % } ``` bash REGISTRY_API_KEY=your-local-development-key \ TOOL_ROOT="$PWD" \ npx tsx src/mcp.ts Vollbildmodus aufrufen Vollbildmodus verlassen In Claude Code fügen Sie den Server hinzu mit:

claude mcp add unified-registry \ --env REGISTRY_API_KEY=your-local-development-key \ --env TOOL_ROOT="$PWD" \ -- npx tsx src/mcp.ts Vollbildmodus aufrufen Vollbildmodus verlassen Für Codex platzieren Sie dieselbe 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" Vollbildmodus aufrufen Vollbildmodus verlassen Beide Agents entdecken read_file und calculate nun über den Registry-Vertrag. Sie sehen identische Schemas, unabhängig davon, welcher Modell-Provider den Aufruf erzeugt hat.

Wenn Sie eine direkte HTTP-Integration bevorzugen, exponieren Sie den Discovery-Katalog als OpenAI-kompatible Funktionsdefinitionen:

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 können diesen Katalog über ` GET / v1 / tools ` abrufen und die daraus resultierenden Funktionsaufrufe an ` POST / v1 / invocations ` übergeben. ## 10. Observability ergänzen Eine Registry ohne Logs lässt sich nicht auditieren. Halte fest, wer was aufgerufen hat, ob es erfolgreich war und wie lange es gedauert hat.

Das ` ToolResult ` enthält bereits ` durationMs `. Der Logger von Fastify erfasst Metadaten auf HTTP-Ebene. Füge innerhalb der Invocation-Route ein strukturiertes Audit-Event hinzu: ``` 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", ); Enter fullscreen mode Exit fullscreen mode Für den Produktivbetrieb sollen diese Events an OpenTelemetry übermittelt werden, eine Korrelations-ID aus der Client-Anfrage enthalten und Policy-Ablehnungen getrennt von Ausführungsfehlern aufgezeichnet werden.

Ablehnungen deuten häufig auf falsch konfigurierte Scopes hin oder darauf, dass ein Agent eine unerwartete Aktion versucht.

Die Referenzimplementierung ist ein Ausgangspunkt. Vor dem Deployment gilt es Folgendes zu tun:

Statische Keys durch OIDC ersetzen. Prüfe Issuer, Audience, Ablaufzeit und Signatur. Leite Rollen und Scopes aus verifizierten Claims ab und nicht aus Request-Headern.

Die Tool-Ausführung isolieren. Führe jedes Tool in einem Container, einer gVisor-Sandbox oder einem dedizierten Worker mit read-only Basis-Image, einem eingeschränkten Filesystem-Mount, standardmäßig ohne Netzwerkzugriff sowie CPU- und Speicherlimits aus.

Policys auf Argumentebene ergänzen. Validiere Dateipfade gegen eine Allowlist von Präfixen, begrenze Dateigrößen und verlange für Schreib- oder Löschoperationen eine menschliche Freigabe.

Verträge versionieren. Füge jedem Registry-Eintrag eine Version hinzu. Wenn sich ein Schema inkompatibel ändert, veröffentliche eine neue Version und halte die alte während der Migration verfügbar.

Rate Limiting ergänzen. Begrenze Invocations pro Subject und pro Tool. Eine entgleiste Agent-Schleife sollte auf ein Kontingent stoßen und nicht nachgelagerte Ressourcen erschöpfen.

Secrets verschlüsseln. Nutze einen Secrets Manager und injiziere Zugangsdaten zur Laufzeit der Ausführung in den Tool-Prozess. Lege niemals Secrets im Registry-Katalog oder im MCP-Umgebungsblock einer gemeinsamen Konfigurationsdatei ab.

Den Katalog signieren. Wenn Clients in unterschiedlichen Trust-Domains laufen, veröffentliche ein signiertes Manifest mit Tool-Versionen und Schema-Hashes, damit Clients Manipulationen erkennen können.

Idempotenz unterstützen. Speichere den idempotencyKey mit einer kurzen TTL. Wenn ein Client nach einem Netzwerk-Timeout erneut anfragt, liefere das ursprüngliche Ergebnis zurück, statt das Tool zweimal auszuführen.

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" ); } ); } ); Enter fullscreen mode Exit fullscreen mode Führe die Suite aus:

npm test npm run typecheck Enter fullscreen mode Exit fullscreen mode Starte den Server und prüfe die API:

REGISTRY_API_KEY = dev-key npm run start Enter fullscreen mode Exit fullscreen mode In einem anderen 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 Enter fullscreen mode Exit fullscreen mode Die Berechnung liefert 2,5. Der Katalog listet beide Tools mit ihren JSON Schemas auf.

Direkte Verbindungen funktionieren für einen Prototyp, vermehren aber die Trust-Boundary. Mit einer Registry erhältst du einen Audit-Trail, eine einzige Schema-Source-of-Truth, eine Policy-Engine und einen einzigen Ort zum Rotieren von Zugangsdaten. Agents erreichen weiterhin MCP-Server, allerdings über einen regulierten Adapter.

Die Authentifizierung bleibt innerhalb der Tool-Implementierung. Die Registry entscheidet, ob ein Aufrufer das Tool ausführen darf. Das Tool wiederum authentifiziert sich gegenüber seinem nachgelagerten Dienst mit Zugangsdaten, die zur Laufzeit injiziert werden. Diese Trennung hält die Registry generisch und verhindert, dass sie zu einem Credential Store wird.

Ja, solange das Tool zustandslos ist oder einen Kontext pro Invocation verwendet. Übergebe Subject und Korrelations-ID des Aufrufers in den Handler-Kontext, damit nachgelagerte Systeme eine Tenant-Isolation durchsetzen können. Hält ein Tool einen veränderlichen Zustand, sollte dieser nach Subject geschlüsselt sein oder das Tool pro Invocation in einem isolierten Prozess laufen.

Du hast nun eine einzige regulierte API, die Claude Code, Codex und MCP-Clients gemeinsam nutzen können. Tools werden über einen Katalog entdeckt, über eine Policy-Engine autorisiert, hinter einer Runtime ausgeführt und an einem Ort auditiert. Der nächste Schritt besteht darin, ein Write-Tool mit Einschränkungen auf Argumentebene und menschlicher Freigabe hinzuzufügen und anschließend die Ausführung in Container zu verlagern, bevor die Registry für entfernte Agents freigegeben wird.

Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.

Original (Englisch) anzeigen

Posted on Nov 24 • Originally published at tamiz.pro

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.

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 │ └──────────┘ └──────────┘ └────────────┘ Enter fullscreen mode Exit fullscreen mode Four layers matter:

The key invariant: all clients receive the same schema and the same authorization decision.

node --version npm --version Enter fullscreen mode Exit fullscreen mode 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 Enter fullscreen mode Exit fullscreen mode 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" ] } Enter fullscreen mode Exit fullscreen mode 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" Enter fullscreen mode Exit fullscreen mode 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.

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; }; Enter fullscreen mode Exit fullscreen mode 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 Enter fullscreen mode Exit fullscreen mode 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, }, ]; Enter fullscreen mode Exit fullscreen mode 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.

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.

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 ); } } } Enter fullscreen mode Exit fullscreen mode 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.

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" } ); Enter fullscreen mode Exit fullscreen mode Notice that discovery is filtered by policy.

A client never sees tools it cannot call. This prevents leaking internal capabilities through the catalog.

Authentication and authorization belong in separate modules so you can swap the identity provider without touching tool code.

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" ], }; } Enter fullscreen mode Exit fullscreen mode The static API key is acceptable for local development. Replace it with OIDC token verification for production.

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" }; } Enter fullscreen mode Exit fullscreen mode 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.

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.

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 ( ) ); } Enter fullscreen mode Exit fullscreen mode The MCP adapter uses the same runtime.execute path as the HTTP API. There is no separate authorization logic.

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 Enter fullscreen mode Exit fullscreen mode 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 Enter fullscreen mode Exit fullscreen mode 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" Enter fullscreen mode Exit fullscreen mode 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", ); Enter fullscreen mode Exit fullscreen mode 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.

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.

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" ); } ); } ); Enter fullscreen mode Exit fullscreen mode Run the suite:

npm test npm run typecheck Enter fullscreen mode Exit fullscreen mode Start the server and verify the API:

REGISTRY_API_KEY = dev-key npm run start Enter fullscreen mode Exit fullscreen mode 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 Enter fullscreen mode Exit fullscreen mode The calculation returns 2.5. The catalog lists both tools with their JSON Schemas.

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.

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.

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.

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.

Originaltitel: The Agentic IDE Is an API: Building a Unified Tool Registry for Claude Code, Codex, and MCPQuelle: dev.to (dev.to). Original öffnen