> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ctxprotocol.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK Reference

> Complete API reference for @ctxprotocol/sdk: installation, configuration, methods, and types

<Note>
  Looking for Python? Check out the [Python SDK Reference](/sdk/python-reference).
</Note>

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @ctxprotocol/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @ctxprotocol/sdk
  ```

  ```bash yarn theme={null}
  yarn add @ctxprotocol/sdk
  ```
</CodeGroup>

### Requirements

* Node.js 18+ (for native fetch)
* TypeScript 5+ (recommended)

***

## Prerequisites

Before using the API, complete setup at [ctxprotocol.com](https://ctxprotocol.com):

<Steps>
  <Step title="Sign in">
    Creates your embedded wallet
  </Step>

  <Step title="Set spending cap">
    Approve USDC spending on the ContextRouter (one-time setup)
  </Step>

  <Step title="Fund wallet">
    Add USDC for tool execution fees
  </Step>

  <Step title="Generate API key">
    In Settings page
  </Step>
</Steps>

***

## Quick Start

```typescript theme={null}
import { ContextClient } from "@ctxprotocol/sdk";

const client = new ContextClient({
  apiKey: "sk_live_...",
});

const answer = await client.query.run({
  query: "What are the top whale movements on Base?",
  responseShape: "answer_with_evidence",
});

console.log(answer.response);
console.log(answer.summary);
console.log(answer.evidence?.facts);
```

<Info>
  **Want per-call pricing and spending limits?** The SDK also supports [Execute mode](#tools-execute-mode) for direct method calls inside session budgets. See [Two SDK Modes](#two-sdk-modes) below.
</Info>

<Tip>
  Building a daily report or repeatable analyst job? See [Agent Data Routines](/sdk/agent-routines) and the runnable TypeScript example at [`examples/client/src/agent-routine.ts`](https://github.com/ctxprotocol/sdk/blob/main/examples/client/src/agent-routine.ts).
</Tip>

***

## Two SDK Modes

The SDK offers two payment models:

| Mode        | Method                   | Payment Model                  | Use Case                                                      |
| ----------- | ------------------------ | ------------------------------ | ------------------------------------------------------------- |
| **Query**   | `client.query.run()`     | Pay-per-response               | Complex questions, multi-tool synthesis, curated intelligence |
| **Execute** | `client.tools.execute()` | Per call (with spending limit) | Deterministic pipelines, raw outputs, explicit cost control   |

<Info>
  **You have access to both modes. Pick the one that fits your use case.**

  * Use **Query** (`client.query.run()`) when you want a managed librarian contract where Context handles discovery/orchestration (up to 100 MCP calls per response turn) and returns `answer_with_evidence` or `evidence_only`. Pay-per-response (\~\$0.10).
  * Use **Execute** (`client.tools.execute()`) when your app/agent is the librarian and you want per-call pricing with spending limits (\~\$0.001/call).

  Most developers start with Query and add Execute later for specific pipelines that need raw data or explicit cost control. You can use both in the same application.
</Info>

### Execute Quick Start

```typescript theme={null}
const executeTools = await client.discovery.search({
  query: "gas prices",
  mode: "execute",
  surface: "execute",
  requireExecutePricing: true,
});

const method = executeTools[0]?.mcpTools?.[0];
if (!method) throw new Error("No execute method available");

const session = await client.tools.startSession({ maxSpendUsd: "1.00" });
const result = await client.tools.execute({
  toolId: executeTools[0].id,
  toolName: method.name,
  args: { chainId: 1 },
  sessionId: session.session.sessionId ?? undefined,
});
console.log(result.result);
console.log(result.session); // methodPrice, spent, remaining, maxSpend, status...
```

<Tip>
  **Full working example:** See [`examples/client/src/execute.ts`](https://github.com/ctxprotocol/sdk/tree/main/examples/client/src/execute.ts) for a complete Execute-mode client with multi-call session management and spend tracking.
</Tip>

<Note>
  Mixed listings are first-class: one listing can expose methods to both modes. Methods without explicit execute pricing remain discoverable for Query but are excluded from Execute discovery when `requireExecutePricing=true`.
</Note>

<Note>
  Compatibility: payload fields like `price` and `pricePerQuery` are kept for backward compatibility. In Query mode, they represent listing-level **price per response turn**.
  A future major release can add response-named aliases (for example, `pricePerResponse`) before deprecating legacy names.
</Note>

***

## Configuration

### Client Options

| Option    | Type     | Required | Default                       | Description                    |
| --------- | -------- | -------- | ----------------------------- | ------------------------------ |
| `apiKey`  | `string` | Yes      | -                             | Your Context Protocol API key  |
| `baseUrl` | `string` | No       | `https://www.ctxprotocol.com` | API base URL (for development) |

```typescript theme={null}
// Production
const client = new ContextClient({
  apiKey: process.env.CONTEXT_API_KEY!,
});

// Local development
const client = new ContextClient({
  apiKey: "sk_test_...",
  baseUrl: "http://localhost:3000",
});
```

***

## API Reference

### Discovery

#### `client.discovery.search(query, limit?)`

#### `client.discovery.search(options)`

Search for tools matching a query string, or pass an options object for mode-aware filtering.

**Parameters (string signature):**

| Parameter | Type     | Required | Description               |
| --------- | -------- | -------- | ------------------------- |
| `query`   | `string` | Yes      | Search query              |
| `limit`   | `number` | No       | Maximum results to return |

**Parameters (options signature):**

| Option                  | Type                                               | Required | Description                                                          |
| ----------------------- | -------------------------------------------------- | -------- | -------------------------------------------------------------------- |
| `query`                 | `string`                                           | No       | Search query (empty for featured-style searches)                     |
| `limit`                 | `number`                                           | No       | Maximum results to return                                            |
| `mode`                  | `"query" \| "execute"`                             | No       | Discovery mode with billing semantics                                |
| `surface`               | `"answer" \| "execute" \| "both"`                  | No       | Method mode filter                                                   |
| `queryEligible`         | `boolean`                                          | No       | Require methods that are query-safe                                  |
| `requireExecutePricing` | `boolean`                                          | No       | Require explicit method execute pricing                              |
| `excludeLatencyClasses` | `("instant" \| "fast" \| "slow" \| "streaming")[]` | No       | Exclude by latency class                                             |
| `excludeSlow`           | `boolean`                                          | No       | Convenience filter for query mode                                    |
| `favoritesOnly`         | `boolean`                                          | No       | Override the account-level Favorites-Only Auto Mode for this request |

**Returns:** `Promise<Tool[]>`

```typescript theme={null}
const tools = await client.discovery.search("ethereum gas", 10);

const executeTools = await client.discovery.search({
  query: "ethereum gas",
  mode: "execute",
  surface: "execute",
  requireExecutePricing: true,
});

const favoriteOnlyTools = await client.discovery.search({
  query: "crypto",
  favoritesOnly: true,
});
```

<Info>
  If you enable Favorites-Only Auto Mode in [Settings](https://ctxprotocol.com/settings), SDK discovery and query requests made with the same API key inherit that account default automatically. Set `favoritesOnly: true` or `favoritesOnly: false` per request to override it. On Query requests with explicit `tools`, manual tool selection wins and `favoritesOnly` is ignored.
</Info>

***

#### `client.discovery.getFeatured(limit?, options?)`

Get featured/popular tools.

**Parameters:**

| Parameter | Type                                      | Required | Description               |
| --------- | ----------------------------------------- | -------- | ------------------------- |
| `limit`   | `number`                                  | No       | Maximum results to return |
| `options` | `Omit<SearchOptions, "query" \| "limit">` | No       | Optional mode filters     |

**Returns:** `Promise<Tool[]>`

```typescript theme={null}
const featured = await client.discovery.getFeatured(5);
const featuredExecute = await client.discovery.getFeatured(5, {
  mode: "execute",
  requireExecutePricing: true,
});
```

#### `client.discovery.get(toolId)`

Fetch one tool listing by UUID.

**Parameters:**

| Parameter | Type     | Required | Description           |
| --------- | -------- | -------- | --------------------- |
| `toolId`  | `string` | Yes      | Marketplace tool UUID |

**Returns:** `Promise<Tool>`

```typescript theme={null}
const tool = await client.discovery.get("uuid-of-tool");
console.log(tool.name);
console.log(tool.mcpTools);
```

***

### Tools (Execute Mode)

#### `client.tools.execute(options)`

Execute a single tool method. Execute calls can run inside a session budget (`maxSpendUsd`) with automatic payment after delivery.

**Parameters:**

| Option           | Type        | Required | Description                                        |
| ---------------- | ----------- | -------- | -------------------------------------------------- |
| `toolId`         | `string`    | Yes      | UUID of the tool                                   |
| `toolName`       | `string`    | Yes      | Name of the method to call                         |
| `args`           | `object`    | No       | Arguments matching the tool's `inputSchema`        |
| `idempotencyKey` | `string`    | No       | Optional idempotency key (UUID recommended)        |
| `mode`           | `"execute"` | No       | Explicit mode label (defaults to `"execute"`)      |
| `sessionId`      | `string`    | No       | Execute session ID to accrue spend against         |
| `maxSpendUsd`    | `string`    | No       | Optional inline session budget (if no `sessionId`) |
| `closeSession`   | `boolean`   | No       | Request session closure after this call settles    |

**Returns:** `Promise<ExecutionResult>`

```typescript theme={null}
const session = await client.tools.startSession({ maxSpendUsd: "2.50" });

const result = await client.tools.execute({
  toolId: "uuid-of-tool",
  toolName: "get_gas_prices",
  args: { chainId: 1 },
  idempotencyKey: crypto.randomUUID(),
  sessionId: session.session.sessionId ?? undefined,
});

console.log(result.method.executePriceUsd); // explicit method price
console.log(result.session); // { methodPrice, spent, remaining, maxSpend, ... }
```

#### `client.tools.startSession({ maxSpendUsd })`

Start an execute session budget envelope.

```typescript theme={null}
const started = await client.tools.startSession({ maxSpendUsd: "5.00" });
console.log(started.session.sessionId);
console.log(started.session.maxSpend);
```

#### `client.tools.getSession(sessionId)`

Fetch current execute session status/spend.

```typescript theme={null}
const status = await client.tools.getSession("sess_123");
console.log(status.session.status); // open | closed | expired
console.log(status.session.spent);
```

#### `client.tools.closeSession(sessionId)`

Close an execute session and trigger final flush behavior.

```typescript theme={null}
const closed = await client.tools.closeSession("sess_123");
console.log(closed.session.status); // closed
```

***

### Developer

#### `client.developer.updateTool(toolId, updates)`

Update contributor-owned tool metadata programmatically. This is for developers managing their own listings, not for buyer query execution.

**Parameters:**

| Parameter                  | Type       | Required | Description             |
| -------------------------- | ---------- | -------- | ----------------------- |
| `toolId`                   | `string`   | Yes      | Tool UUID               |
| `updates.name`             | `string`   | No       | New display name        |
| `updates.description`      | `string`   | No       | New description         |
| `updates.suggestedPrompts` | `string[]` | No       | Suggested buyer prompts |
| `updates.category`         | `string`   | No       | Listing category        |

**Returns:** `Promise<UpdateToolResult>`

```typescript theme={null}
const updated = await client.developer.updateTool("uuid-of-tool", {
  description: "Updated coverage and data freshness notes.",
  suggestedPrompts: ["Which Base wallets had the largest inflows today?"],
});

console.log(updated.tool);
```

***

### Query (Pay-Per-Response)

<Info>
  The Query API is Context's **response marketplace**. Instead of buying raw API calls, you're buying curated intelligence. Ask a question, pay once, and get a grounded, managed answer.
</Info>

#### `client.query.run(options)`

Run an agentic query. The managed runtime handles tool discovery, ambiguity resolution, multi-tool execution (up to 100 MCP calls per response turn as a safety cap), and grounding — and returns the selected Query response contract (`answer_with_evidence` or `evidence_only`, default `answer_with_evidence`). Query billing is pay-per-response with automatic payment after delivery.

**Parameters:**

| Option                  | Type                                                        | Required | Description                                                                                      |
| ----------------------- | ----------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------ |
| `query`                 | `string`                                                    | Yes      | Natural-language question                                                                        |
| `tools`                 | `string[]`                                                  | No       | Tool IDs to use (auto-discover if omitted)                                                       |
| `favoritesOnly`         | `boolean`                                                   | No       | Override the account-level Favorites-Only Auto Mode for this request                             |
| `agentModelId`          | `string`                                                    | No       | Main librarian agent model ID (omit to use `DEFAULT_AGENT_MODEL_ID`)                             |
| `responseShape`         | `"answer_with_evidence" \| "evidence_only"`                 | No       | Structured response mode (default: `answer_with_evidence`).                                      |
| `includeData`           | `boolean`                                                   | No       | Include bounded execution data inline. Large payloads return a preview plus full-data references |
| `includeDataUrl`        | `boolean`                                                   | No       | Persist execution data to blob and return a URL                                                  |
| `includeDeveloperTrace` | `boolean`                                                   | No       | Include optional developer trace + orchestration diagnostics                                     |
| `idempotencyKey`        | `string`                                                    | No       | Optional idempotency key (UUID recommended)                                                      |
| `resumeFrom`            | `{ sessionId: string; attemptId: string }`                  | No       | Resume from a previous Query attempt handle                                                      |
| `forkFrom`              | `{ sessionId: string; attemptId: string; reason?: string }` | No       | Fork a previous Query attempt into a new branch                                                  |

Can also accept a plain string: `client.query.run("your question")`

**Returns:** `Promise<QueryResult>`

```typescript theme={null}
const answer = await client.query.run("What are the top whale movements on Base?");
console.log(answer.response);     // response text or summary
console.log(answer.toolsUsed);    // [{ id, name, skillCalls }]
console.log(answer.cost);         // { modelCostUsd, toolCostUsd, totalCostUsd }
// `orchestrationMetrics` and `developerTrace` are only populated when
// `includeDeveloperTrace: true` is passed — see the next example.
```

```typescript theme={null}
const answer = await client.query.run({
  query: "Analyze whale activity on Base",
  favoritesOnly: true,
  agentModelId: "kimi-k2.6-model",
  responseShape: "answer_with_evidence",
  includeData: true,
  includeDataUrl: true,
  includeDeveloperTrace: true,
  idempotencyKey: crypto.randomUUID(),
});

console.log(answer.responseShape); // "answer_with_evidence"
console.log(answer.summary); // short machine-friendly summary
console.log(answer.evidence?.facts); // canonical evidence facts
console.log(answer.artifacts?.dataUrl); // artifact refs used by the answer package
console.log(answer.freshness?.asOf); // freshness metadata
console.log(answer.confidence?.level); // high | medium | low
console.log(answer.developerTrace?.summary); // retries/fallbacks/loops summary
console.log(answer.developerTrace?.diagnostics?.selection); // internal runtime policy diagnostics
console.log(answer.orchestrationMetrics); // first-pass / capability-miss / rediscovery metrics (gated on includeDeveloperTrace)
```

<Note>
  `agentModelId` lets headless users choose the main librarian agent model explicitly. If omitted, the API uses its managed default agent model. Internal tool selection remains managed by the server.
  If `responseShape` is `evidence_only`, Context skips the extra prose synthesis layer, but the librarian agent still runs to fetch, compute, and ground the result.

  Import `AGENT_MODEL_IDS` and `DEFAULT_AGENT_MODEL_ID` from `@ctxprotocol/sdk` to see the current supported slugs. Omit `agentModelId` to use the managed default (`DEFAULT_AGENT_MODEL_ID`).
</Note>

<Info>
  The query runtime now exposes a single managed executor surface.
  The server decides internal budgets, ambiguity handling, and exploration policy from the query itself instead of asking SDK callers to choose a lane.

  `includeDeveloperTrace` and `orchestrationMetrics` are optional diagnostic surfaces that are **both gated on `includeDeveloperTrace: true`** — they are `undefined` on the response envelope when the flag is omitted. Their inner fields are typed but may evolve across rollouts as the managed runtime changes, so treat them as debugging signals rather than a stable execution contract.

  The `developerTrace` object mirrors the chat app's Developer Logs card (same iterative-runtime signals): `orchestrationMode: "query"`, `summary` (tool calls, retries, loop steps), `timeline`, `toolCallHistory` (with `isCodeInterpreter` flags on Python sandbox calls), `executionTrace`, `verification` (with `boundedAnswerReason` / `boundedAnswerDataGap` when a safety guardrail stopped retries), and `diagnostics` (selection, execution contract, cost, contributor searches, tool-registry stats, retry budget, stage timing). The `initialCode` / `finalCode` fields are the `// iterative execution: no generated code` sentinel kept for trace compatibility with the previous VM-based runtime — no JavaScript is generated or executed.
</Info>

#### Structured Response Shapes

Query is Context's managed librarian contract. You can choose how much structure you want back:

| `responseShape`        | Best for                                      | Behavior                                                                                    |
| ---------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `answer_with_evidence` | First-party chat, human-facing apps (default) | Prose answer plus structured evidence, artifacts, freshness, confidence, and usage metadata |
| `evidence_only`        | External agents, downstream automation        | Bounded evidence, computed artifacts, and full-data references without prose synthesis      |

The first-party chat app defaults to `answer_with_evidence`, but it is using the same Query contract you get in the SDK.

#### Query Envelope Fields

When `responseShape` is `answer_with_evidence` or `evidence_only`, the result may include:

| Field        | What it contains                                                                                                                    |
| ------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| `summary`    | Short machine-friendly summary of the answer                                                                                        |
| `evidence`   | Canonical facts, source refs, assumptions, known unknowns, retrieval reason codes, and optional wedge-specific `marketIntelligence` |
| `artifacts`  | `dataUrl`, canonical dataset metadata, and stage-artifact kinds                                                                     |
| `view`       | Optional UI/render hint such as `table`, `leaderboard`, `heatmap`, or `timeseries`, plus optional `metrics`, `columns`, and `rows`  |
| `outcome`    | Public outcome label, tone, `stopReason`, and optional `issueClass`                                                                 |
| `controller` | Public bounded-controller summary including `actionsTaken`, `nextAction`, and patch-preservation flags                              |
| `freshness`  | `asOf`, source timestamps, and freshness note                                                                                       |
| `confidence` | Confidence level, reason, fact counts, and gap signals                                                                              |
| `usage`      | Duration, cost, tools used, outcome type, and optional orchestration metrics                                                        |

```typescript theme={null}
const result = await client.query.run({
  query: "Which exchanges are seeing the largest BTC inflows and outflows over the last 24 hours?",
  responseShape: "evidence_only",
});

console.log(result.response); // machine-friendly summary for evidence_only
console.log(result.summary);
console.log(result.evidence?.sourceRefs);
console.log(result.evidence?.marketIntelligence?.venueBreakdown);
console.log(result.stopReason, result.issueClass, result.actionsTaken);
console.log(result.usage?.toolsUsed);
```

#### High-Fidelity Rehydration (Retrieval-First Synthesis)

When retrieval-first rollout is enabled in the deployment, the query runtime can switch synthesis context assembly from baseline truncation to retrieval-first slices for full-data or truncation-sensitive requests.

* Stage artifacts are emitted in request-scoped internal storage (selection, execution, synthesis). The `scout` stage is a legacy artifact slot — scout probe execution is disabled in the current iterative runtime, so no scout stage artifacts are produced.
* Retrieval primitives (path lookup, array windows/sampling, keyword slices, top-K relevance) are used to build a bounded context pack from canonical execution data.
* Final synthesis still passes through the existing synthesis safety contract.
* `includeData` returns a bounded inline preview when needed, and `includeDataUrl`/`artifacts.canonicalDataRef` reference the same canonical execution dataset used by retrieval-first assembly.

#### Resume and Fork

Every Query response can include `querySession` handles. Use `resumeFrom` to continue from a previous attempt, or `forkFrom` to branch from an attempt while preserving lineage.

```typescript theme={null}
const first = await client.query.run({
  query: "Find the biggest Base whale movements today",
  includeDeveloperTrace: true,
});

const handle = first.querySession;
if (handle) {
  const resumed = await client.query.run({
    query: "Focus only on wallets with exchange interactions",
    resumeFrom: {
      sessionId: handle.sessionId,
      attemptId: handle.attemptId,
    },
  });

  const forked = await client.query.run({
    query: "Try the same question with stricter evidence requirements",
    forkFrom: {
      sessionId: handle.sessionId,
      attemptId: handle.attemptId,
      reason: "manual_fork",
    },
  });

  console.log(resumed.response);
  console.log(forked.response);
}
```

#### `client.query.stream(options)`

Same as `run()` but streams events in real-time via SSE.

Supports the same options as `run()` (`tools`, `favoritesOnly`, `agentModelId`, `responseShape`, `includeData`, `includeDataUrl`, `includeDeveloperTrace`, `idempotencyKey`).

**Returns:** `AsyncGenerator<QueryStreamEvent>`

```typescript theme={null}
for await (const event of client.query.stream({
  query: "What are the top whale movements?",
})) {
  switch (event.type) {
    case "tool-status":
      console.log(`Tool ${event.tool.name}: ${event.status}`);
      break;
    case "text-delta":
      process.stdout.write(event.delta);
      break;
    case "done":
      console.log("\nTotal cost:", event.result.cost.totalCostUsd);
      break;
  }
}
```

<Note>
  Use the same `idempotencyKey` when retrying the same logical request after network/timeout failures.
</Note>

<Note>
  If you stream with `responseShape: "evidence_only"`, expect the structured result on the final `done` event and few or no `text-delta` events.
</Note>

<Note>
  `query.run()` uses the streaming path internally and has a default stream timeout of 600 seconds. Non-streaming SDK requests default to 300 seconds. For complex chart-heavy requests, use async jobs.
</Note>

#### Async Query Jobs

Use async jobs when a query may exceed a single blocking SDK request.

```typescript theme={null}
const job = await client.query.start({
  query: "Build a chart-ready dataset of Base whale movements over the last 30 days",
  responseShape: "evidence_only",
  includeDataUrl: true,
});

const status = await client.query.getStatus(job.jobId);
console.log(status.status); // queued | running | completed | failed

const completed = await client.query.poll(job.jobId, {
  intervalMs: 2000,
  timeoutMs: 15 * 60_000,
});
console.log(completed.result);
```

***

## Types

### Import Types

```typescript theme={null}
import {
  // Auth utilities for tool contributors
  verifyContextRequest,
  isProtectedMcpMethod,
  isOpenMcpMethod,
} from "@ctxprotocol/sdk";

import type {
  // Client types
  ContextClientOptions,
  Tool,
  McpTool,
  McpToolMeta,
  McpToolRateLimitHints,
  ExecuteOptions,
  ExecutionResult,
  QueryOptions,
  QueryResult,
  QueryDeveloperTrace,
  QueryOrchestrationMetrics,
  QueryResponseEnvelope,
  QueryComputedArtifact,
  QueryCapabilityMissPayload,
  QueryAssumptionMetadata,
  ContextErrorCode,
  // Auth types (for MCP server contributors)
  VerifyRequestOptions,
  // Context types (for MCP server contributors receiving injected data)
  ContextRequirementType,
  HyperliquidContext,
  PolymarketContext,
  WalletContext,
  UserContext,
} from "@ctxprotocol/sdk";
```

***

### Tool

```typescript theme={null}
interface Tool {
  id: string;
  name: string;
  description: string;
  price: string; // Listing-level response price metadata (legacy field name)
  category?: string;
  isVerified?: boolean;
  mcpTools?: McpTool[];
}
```

***

### McpTool

```typescript theme={null}
interface McpTool {
  name: string;
  description: string;
  inputSchema?: Record<string, unknown>;   // JSON Schema for arguments
  outputSchema?: Record<string, unknown>;  // JSON Schema for response
  _meta?: McpToolMeta;                     // mode/eligibility/pricing/context metadata
  executeEligible?: boolean;               // derived discovery field
  executePriceUsd?: string | null;         // explicit execute price visibility
}

interface McpToolRateLimitHints {
  maxRequestsPerMinute?: number;
  maxConcurrency?: number;
  cooldownMs?: number;
  supportsBulk?: boolean;
  recommendedBatchTools?: string[];
  notes?: string;
}

interface McpToolMeta {
  surface?: "answer" | "execute" | "both";
  queryEligible?: boolean;
  latencyClass?: "instant" | "fast" | "slow" | "streaming";
  pricing?: {
    executeUsd?: string; // required for execute eligibility
    queryUsd?: string;   // optional metadata only in this rollout
  };
  executeEligible?: boolean;
  executePriceUsd?: string;
  contextRequirements?: ContextRequirementType[];
  rateLimit?: McpToolRateLimitHints;
  rateLimitHints?: McpToolRateLimitHints;
}
```

<Info>
  For argument guidance, use standard JSON Schema fields directly inside `inputSchema` properties. Put fallback values in `default` and sample invocations in `examples`. Do not rely on custom `_meta.inputExamples`.
</Info>

```typescript theme={null}
const TOOLS = [{
  name: "get_price_history",
  inputSchema: {
    type: "object",
    properties: {
      symbol: { type: "string", default: "BTC", examples: ["BTC", "ETH", "SOL"] },
      interval: { type: "string", enum: ["1h", "4h", "1d"], default: "1h", examples: ["1h", "4h"] },
      limit: { type: "number", default: 100, examples: [50, 100, 200] },
    },
    required: [],
  },
}];
```

***

### ExecutionResult (Execute Mode)

```typescript theme={null}
interface ExecutionResult<T = unknown> {
  mode: "execute";
  result: T;
  tool: { id: string; name: string };
  method: { name: string; executePriceUsd: string };
  session: ExecuteSessionSpend;
  durationMs: number;
}
```

### ExecuteSessionSpend

```typescript theme={null}
interface ExecuteSessionSpend {
  mode: "execute";
  sessionId: string | null;
  methodPrice: string;
  spent: string;
  remaining: string | null;
  maxSpend: string | null;
  status?: "open" | "closed" | "expired";
  expiresAt?: string;
  closeRequested?: boolean;
  pendingAccruedCount?: number;
  pendingAccruedUsd?: string;
}
```

***

### QueryResult (Pay-Per-Response)

```typescript theme={null}
interface QueryResult {
  response: string;                     // prose answer or machine-friendly summary
  toolsUsed: QueryToolUsage[];          // [{ id, name, skillCalls }]
  cost: QueryCost;                      // { modelCostUsd, toolCostUsd, totalCostUsd }
  durationMs: number;
  data?: unknown;                       // Bounded data/preview when includeData=true
  dataUrl?: string;                     // Optional blob URL (includeDataUrl=true)
  computedArtifacts?: QueryComputedArtifact[]; // Charts/dataframes computed by code_interpreter
  developerTrace?: QueryDeveloperTrace; // Optional runtime trace + diagnostics
  orchestrationMetrics?: QueryOrchestrationMetrics; // Optional first-pass metrics
  responseShape?: "answer_with_evidence" | "evidence_only";
  summary?: string;
  evidence?: QueryResponseEnvelope["evidence"];
  artifacts?: QueryResponseEnvelope["artifacts"];   // Provenance: source refs + dataset handles
  view?: QueryResponseEnvelope["view"];
  freshness?: QueryResponseEnvelope["freshness"];
  confidence?: QueryResponseEnvelope["confidence"];
  usage?: QueryResponseEnvelope["usage"];
  outcomeType: "answer" | "capability_miss";
  capabilityMiss?: QueryCapabilityMissPayload;
  assumptionMade?: QueryAssumptionMetadata;
}
```

***

### Context Requirement Types

For MCP server contributors building tools that need user context (e.g., wallet data, portfolio positions):

<Info>
  **Why Context Injection Matters:**

  * **No Auth Required**: Public blockchain/user data is fetched by the platform, so you don't need to handle API keys or user login.
  * **Security**: Your MCP server never handles private keys or sensitive credentials.
  * **Simplicity**: You receive structured, type-safe data directly in your tool arguments.
</Info>

```typescript theme={null}
import type { ContextRequirementType } from "@ctxprotocol/sdk";

/** Context types supported by the marketplace */
type ContextRequirementType = "polymarket" | "hyperliquid" | "wallet";

// Usage: Declare context requirements in _meta at the tool level (MCP spec)
const TOOLS = [{
  name: "analyze_my_positions",
  description: "Analyze your positions with personalized insights",

  // REQUIRED: Context requirements in _meta (MCP spec for arbitrary metadata)
  // The Context platform reads this to inject user data + pacing hints
  _meta: {
    contextRequirements: ["hyperliquid"] as ContextRequirementType[],
    rateLimit: {
      maxRequestsPerMinute: 30,
      cooldownMs: 2000,
      maxConcurrency: 1,
      supportsBulk: true,
      recommendedBatchTools: ["get_portfolio_snapshot"],
      notes: "Hobby tier: use snapshot methods before per-asset loops.",
    },
  },

  inputSchema: {
    type: "object",
    properties: {
      portfolio: { 
        type: "object",
        description: "Portfolio context (injected by platform)",
      },
    },
    required: ["portfolio"],
  },
  outputSchema: { /* ... */ },
}];
```

<Info>
  **Why `_meta` at the tool level?** The `_meta` field is part of the [MCP specification](https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool-definition) for arbitrary tool metadata. The Context platform reads `_meta.contextRequirements` for context injection and `_meta.rateLimit` / `_meta.rateLimitHints` for runtime pacing behavior. This is preserved through MCP transport because it's a standard field.
</Info>

<Info>
  Reference implementation: [Coinglass contributor server](https://github.com/ctxprotocol/sdk/tree/main/examples/server/coinglass-contributor).
</Info>

<Info>
  For when/how to set these fields, see [Tool Metadata](/guides/tool-metadata#rate-limit-hints).
</Info>

***

### Injected Context Types

#### HyperliquidContext

```typescript theme={null}
interface HyperliquidContext {
  walletAddress: string;
  perpPositions: HyperliquidPerpPosition[];
  spotBalances: HyperliquidSpotBalance[];
  openOrders: HyperliquidOrder[];
  accountSummary: HyperliquidAccountSummary;
  fetchedAt: string;
}
```

#### PolymarketContext

```typescript theme={null}
interface PolymarketContext {
  walletAddress: string;
  positions: PolymarketPosition[];
  openOrders: PolymarketOrder[];
  totalValue?: number;
  fetchedAt: string;
}
```

#### WalletContext

```typescript theme={null}
interface WalletContext {
  address: string;
  chainId: number;
  nativeBalance?: string;
}

interface ERC20TokenBalance {
  address: string;
  symbol: string;
  decimals: number;
  balance: string;
}

interface ERC20Context {
  tokens: ERC20TokenBalance[];
}
```

***

## Contributor Search Helpers

If you are building a contributor for a search-hard venue, the SDK ships an optional helper surface at `@ctxprotocol/sdk/contrib/search`.

Use it only when the venue's upstream search is weak enough that deterministic retrieval plus a bounded model judge materially improves candidate resolution. Do **not** use it for venues that already expose reliable direct search.

```typescript theme={null}
import {
  buildContributorSearchValidationArtifact,
  createSearchIntent,
  extractContributorSearchesFromDeveloperTrace,
  mergeContributorSearchConfig,
  resolveContributorSearch,
} from "@ctxprotocol/sdk/contrib/search";
```

What this module is for:

* contributor-side intent shaping, candidate normalization, shortlist construction, and validated resolution
* provider-agnostic judge injection with stable override knobs for `provider`, `model`, `timeout`, `budget`, and `disabled`
* machine-readable artifact generation via `buildContributorSearchValidationArtifact(...)`
* runtime trace inspection via `extractContributorSearchesFromDeveloperTrace(trace)` or `result.developerTrace?.diagnostics?.contributorSearches`

Operational rules:

* extra judge spend is contributor-owned in this rollout, so recover it through your own listing response price and/or execute pricing
* keep deterministic validation around every judge result; malformed, timed-out, over-budget, or contradictory judgments must degrade honestly
* save replayable validation artifacts alongside your contributor examples. Current reference directories live under `examples/server/polymarket-contributor/validation/` and `examples/server/kalshi-contributor/validation/`

***

## Error Handling

The SDK throws `ContextError` with specific error codes:

```typescript theme={null}
import { ContextError } from "@ctxprotocol/sdk";

try {
  const result = await client.tools.execute({ ... });
} catch (error) {
  if (error instanceof ContextError) {
    switch (error.code) {
      case "no_wallet":
        // User needs to set up wallet
        console.log("Setup required:", error.helpUrl);
        break;
      case "insufficient_allowance":
        // User needs to set a spending cap
        console.log("Set spending cap:", error.helpUrl);
        break;
      case "payment_failed":
        // Insufficient USDC balance
        break;
      case "execution_failed":
        // Tool execution error
        break;
    }
  }
}
```

### Error Codes

| Code                     | Description          | Handling                  |
| ------------------------ | -------------------- | ------------------------- |
| `unauthorized`           | Invalid API key      | Check configuration       |
| `no_wallet`              | Wallet not set up    | Direct user to `helpUrl`  |
| `insufficient_allowance` | Spending cap not set | Direct user to `helpUrl`  |
| `payment_failed`         | USDC payment failed  | Check balance             |
| `execution_failed`       | Tool error           | Retry with different args |

***

## Securing Your Tool (MCP Contributors)

If you're building an MCP server, verify incoming requests are legitimate.

<Info>
  **Free vs Paid Security Requirements:**

  | Tool Type                | Security Middleware | Rationale                                      |
  | ------------------------ | ------------------- | ---------------------------------------------- |
  | **Free Tools (\$0.00)**  | **Optional**        | Great for distribution and adoption            |
  | **Paid Tools (\$0.01+)** | **Mandatory**       | We cannot route payments to insecure endpoints |
</Info>

### Quick Implementation

```typescript theme={null}
import express from "express";
import { createContextMiddleware } from "@ctxprotocol/sdk";

const app = express();
app.use(express.json());

// 1 line of code to secure your endpoint
app.use("/mcp", createContextMiddleware());

app.post("/mcp", (req, res) => {
  // req.context contains verified JWT payload (on protected methods)
  // Handle MCP request...
});
```

### MCP Security Model

<Warning>
  **Critical for tool contributors:** Not all MCP methods require authentication. The middleware **selectively** protects only execution methods.
</Warning>

| MCP Method       | Auth Required | Why                                         |
| ---------------- | ------------- | ------------------------------------------- |
| `initialize`     | ❌ No          | Session setup                               |
| `tools/list`     | ❌ No          | Discovery - agents need to see your schemas |
| `resources/list` | ❌ No          | Discovery                                   |
| `prompts/list`   | ❌ No          | Discovery                                   |
| `tools/call`     | ✅ **Yes**     | **Execution - costs money, runs your code** |

<Info>
  **What this means in practice:**

  * ✅ `https://your-mcp.com/mcp` + `initialize` → Works without auth
  * ✅ `https://your-mcp.com/mcp` + `tools/list` → Works without auth
  * ❌ `https://your-mcp.com/mcp` + `tools/call` → **Requires Context Protocol JWT**

  This matches standard API patterns (OpenAPI schemas are public, GraphQL introspection is open).
</Info>

### Manual Verification

For more control, use the lower-level utilities:

```typescript theme={null}
import { 
  verifyContextRequest, 
  isProtectedMcpMethod, 
  ContextError 
} from "@ctxprotocol/sdk";

// Check if a method requires auth
if (isProtectedMcpMethod(body.method)) {
  const payload = await verifyContextRequest({
    authorizationHeader: req.headers.authorization,
    audience: "https://your-tool.com/mcp", // optional
  });
  // payload contains verified JWT claims
}
```

### Verification Options

| Option                | Type     | Required | Description                                         |
| --------------------- | -------- | -------- | --------------------------------------------------- |
| `authorizationHeader` | `string` | Yes      | Full Authorization header (e.g., `"Bearer eyJ..."`) |
| `audience`            | `string` | No       | Expected audience claim for stricter validation     |

***

## Payment Flow

Context supports two settlement timings:

1. **Query mode (`client.query.*`)** uses deferred settlement after the response is delivered
2. **Execute mode (`client.tools.execute`)** accrues per-call method spend into execute sessions with automatic batch payment
3. In both modes, spending caps are enforced via ContextRouter allowance checks
4. **90%** goes to the tool developer, **10%** goes to the protocol

***

## Links

* [Context Protocol](https://ctxprotocol.com)
* [NPM Package](https://www.npmjs.com/package/@ctxprotocol/sdk)
* [GitHub (TypeScript SDK)](https://github.com/ctxprotocol/sdk)
* [Python SDK](/sdk/python-reference)
