Skip to main content
Looking for Python? Check out the Python SDK Reference.

Installation

Requirements

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

Prerequisites

Before using the API, complete setup at ctxprotocol.com:
1

Sign in

Creates your embedded wallet
2

Set spending cap

Approve USDC spending on the ContextRouter (one-time setup)
3

Fund wallet

Add USDC for tool execution fees
4

Generate API key

In Settings page

Quick Start

Want per-call pricing and spending limits? The SDK also supports Execute mode for direct method calls inside session budgets. See Two SDK Modes below.
Building a daily report or repeatable analyst job? See Agent Data Routines and the runnable TypeScript example at examples/client/src/agent-routine.ts.

Two SDK Modes

The SDK offers two payment models:
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.

Execute Quick Start

Full working example: See examples/client/src/execute.ts for a complete Execute-mode client with multi-call session management and spend tracking.
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.
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.

Configuration

Client Options


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): Parameters (options signature): Returns: Promise<Tool[]>
If you enable Favorites-Only Auto Mode in 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.

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

Get featured/popular tools. Parameters: Returns: Promise<Tool[]>

client.discovery.get(toolId)

Fetch one tool listing by UUID. Parameters: Returns: Promise<Tool>

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: Returns: Promise<ExecutionResult>

client.tools.startSession({ maxSpendUsd })

Start an execute session budget envelope.

client.tools.getSession(sessionId)

Fetch current execute session status/spend.

client.tools.closeSession(sessionId)

Close an execute session and trigger final flush behavior.

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: Returns: Promise<UpdateToolResult>

Query (Pay-Per-Response)

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.

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. Since SDK 0.21.0, run() is backed by the durable job path (start() + poll()), so a single call reliably covers the full 1800-second hosted compute ceiling and survives transient connection drops. Pass QueryPollOptions as an optional second argument to shorten the client-side wait. Parameters: Can also accept a plain string: client.query.run("your question") Returns: Promise<QueryResult>
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).
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.

Structured Response Shapes

Query is Context’s managed librarian contract. You can choose how much structure you want back: 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:

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.

client.query.stream(options)

Runs the same query pipeline as run() but over a live SSE connection, yielding events in real-time. Supports the same options as run() (tools, favoritesOnly, agentModelId, responseShape, includeData, includeDataUrl, includeDeveloperTrace, idempotencyKey). Returns: AsyncGenerator<QueryStreamEvent>
Use the same idempotencyKey when retrying the same logical request after network/timeout failures.
If you stream with responseShape: "evidence_only", expect the structured result on the final done event and few or no text-delta events.
query.stream() has a default client stream timeout of 600 seconds (configurable via streamTimeoutMs). query.run() is job-backed since 0.21.0 and is not bound by the stream timeout — it waits up to 31 minutes by default. The hosted compute ceiling is 1800 seconds on every query path — sync, async jobs, and MCP.

client.query.runOrPoll(options, pollOptions?)

Start a durable query job and wait internally until it completes. This is the recommended one-call helper for LLM agents and scheduled agent frameworks because the entire wait happens inside one SDK call (one model turn) instead of asking the host LLM to call getStatus() 20-40 times.
The defaults are agent-friendly: status is checked every 5 seconds over plain HTTP (HTTP polls cost no model tokens — model turns do), and the client waits up to 31 minutes, slightly beyond the 1800-second hosted compute ceiling. Only pass pollOptions if you need a shorter client-side wait. Since 0.21.0, run() and runOrPoll() share the same durable job-backed path, so either works for uncertain query times. runOrPoll() remains the explicit name for readers of agent code.

Async Query Jobs

Use async jobs when a query may exceed a single blocking SDK request.
For LLM agents, prefer runOrPoll() or start() + poll(). Reserve getStatus() loops for normal programs where each check is just an HTTP request, never for LLM agents where each check is a full model turn.

Types

Import Types


Tool


McpTool

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.

ExecutionResult (Execute Mode)

ExecuteSessionSpend


QueryResult (Pay-Per-Response)


Context Requirement Types

For MCP server contributors building tools that need user context (e.g., wallet data, portfolio positions):
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.
Why _meta at the tool level? The _meta field is part of the MCP specification 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.
Reference implementation: Normalized Data Provider — per-method _meta.pricing and _meta.rateLimit in production.
For when/how to set these fields, see Tool Metadata.

Injected Context Types

HyperliquidContext

PolymarketContext

WalletContext


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.
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:

Error Codes


Securing Your Tool (MCP Contributors)

If you’re building an MCP server, verify incoming requests are legitimate.
Free vs Paid Security Requirements:

Quick Implementation

MCP Security Model

Critical for tool contributors: Not all MCP methods require authentication. The middleware selectively protects only execution methods.
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/callRequires Context Protocol JWT
This matches standard API patterns (OpenAPI schemas are public, GraphQL introspection is open).

Manual Verification

For more control, use the lower-level utilities:

Verification Options


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