Skip to main content

Tool Router

Route tool calls and raw HTTP requests through a managed session. Auth is injected server-side, so your agent never touches provider credentials.

1 min read
View MarkdownEdit on GitHub

Tool Router

The Tool Router is the layer that turns a CodeSpar session into a live tool-access endpoint. Once a session exists, your agent can:

  • Execute registered tools via session.execute(tool, params), the standard path for anything in the catalog.
  • Proxy raw HTTP calls via session.proxyExecute(...), for endpoints that don't have a pre-defined tool yet, or when you need provider-specific fields the meta-tools don't expose.
  • Stream as MCP: the session URL is consumable by any MCP-compatible client (Claude Desktop, Cursor, VS Code).

In every case, credentials stay on the server. Your agent sees only the session id; the backend injects the right API key, OAuth token, or certificate per provider and logs the call.

Why a router

Most commerce workflows touch 3 to 6 providers. Without a router, each call forces the agent code to:

  1. Hold the provider credential (security and compliance headache).
  2. Format the request in the provider's native shape.
  3. Handle rate limits, retries, and credential rotation per provider.
  4. Log, audit, and bill the call manually.

With the router, the agent holds one short-lived CodeSpar API key, calls session.execute or session.proxyExecute, and the backend takes care of the rest.

Three ways to call a tool

1. Meta-tool (the default)

const result = await session.execute("codespar_pay", {
  method: "pix",
  amount: 15000,
  currency: "BRL",
  customer: { doc: "12345678900", name: "Maria" },
});

Meta-tools (codespar_pay, codespar_invoice, codespar_ship, codespar_notify, codespar_checkout, codespar_discover) route to the best provider for the region and payment method. The agent doesn't need to know whether the Pix went through Asaas, Zoop, or Mercado Pago: the router picks.

2. Raw provider tool

const result = await session.execute("STRIPE_CREATE_CHARGE", {
  amount: 1000,
  currency: "usd",
  source: "tok_visa",
});

Use when the meta-tool abstraction is too loose and you want the provider's exact field shape. Credentials still injected server-side.

3. Proxy execute (raw HTTP)

const result = await session.proxyExecute({
  server: "stripe",
  endpoint: "/v1/charges",
  method: "POST",
  body: {
    amount: 1000,
    currency: "usd",
    source: "tok_visa",
  },
});

if (result.status === 201) {
  console.log("charge id:", (result.data as { id: string }).id);
}

For anything not yet covered by a registered tool: new provider endpoints, beta APIs, or one-off integrations. The backend still injects auth for the named server, rate-limits, and writes an audit log.

Don't put API keys, bearer tokens, or signed headers in request.headers. The backend injects provider credentials automatically. Headers you pass are forwarded as request metadata only (e.g. Idempotency-Key, X-Trace-Id).

Request shape

interface ProxyRequest {
  server: string;                 // e.g. "stripe", "asaas"
  endpoint: string;               // e.g. "/v1/charges"
  method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
  body?: unknown;                 // JSON body (ignored for GET)
  params?: Record<string, string | number | boolean>;  // query string
  headers?: Record<string, string>;  // request metadata, NOT auth
}

Response shape

interface ProxyResult {
  status: number;                     // upstream HTTP status
  data: unknown;                      // parsed JSON, or string if non-JSON
  headers: Record<string, string>;    // response headers, lowercased
  duration: number;                   // upstream call duration (ms)
  proxy_call_id?: string;             // log cross-reference id
}

On a non-2xx backend response (your session expired, the server isn't connected, rate limit), proxyExecute throws. The status field on the result object is the upstream status: a proxied 401 from Stripe is a successful proxy call that returned 401.

MCP endpoint

Every session exposes an MCP-compatible URL via session.mcp:

const { url, headers } = session.mcp;
// Plug into Claude Desktop, Cursor, VS Code, or any MCP client.

Helpers in @codespar/mcp generate the right config file for each client.

Observability

Every call through the router, whether execute, proxyExecute, or MCP-routed, is logged with:

  • The session id, user id, and account id
  • The tool or endpoint called and the parameters
  • Upstream latency, status, and byte count
  • Retry attempts and final outcome

Stream logs live with codespar logs tail or the backend GET /v1/logs/stream SSE endpoint.

Operating the router

Three dashboard pages cover day-to-day router operations.

Health rollup

/dashboard/health is the at-a-glance status surface. It rolls up six checks: database, credential store, embeddings coverage for discovery, FX-rate freshness, router telemetry activity, and your provider connections. An overall status is derived from them:

  • down: the database or credential store is unreachable. The router cannot operate.
  • degraded: a non-critical check is off nominal, e.g. stale FX rates, idle telemetry, or partial connections. The router operates with reduced quality.
  • healthy: every check is nominal.

Status transitions emit system.health.degraded and system.health.recovered events through the standard triggers pipeline, so you can page on them instead of watching the dashboard. The page deep-links to /dashboard/triggers with the event filter pre-filled.

Per-provider metrics

/dashboard/router shows one row per provider and canonical tool pair: attempts, success rate, p50 upstream latency, the last error code, and a 24-hour latency sparkline. It answers "is it the provider or my dispatch" during an incident. On a healthy rail you should see success rates of 99% or better and an empty last-error column. The same error code repeating row after row usually means credential drift or a provider-side breaking change; confirm on the connections panel of /dashboard/health first, then the provider's status page. Zero attempts on a rail you expect traffic on usually means the tenant has no connection for that provider, so the dispatcher cannot pick it.

Candidates triage

/dashboard/router-candidates is the triage surface for adding new rails to the router. It consumes a classifier-generated report of catalog tools that look like routing candidates for a meta-tool, and lets you mark each candidate as claimed (you will hand-curate the transforms and add the rail), deferred (revisit next sweep), or rejected (wrong classification), then export the claimed set as JSON for hand-curation. The page is browser-only: the report you drop on it never round-trips through the backend, and triage state persists in localStorage keyed by the report's checksum, so a reload does not erase your progress.

Next steps

Tool Router | CodeSpar