### Quick Start Example Source: https://docs.ctxprotocol.com/sdk/python-reference Demonstrates how to initialize the ContextClient, perform a query, and access the response, summary, and evidence. ```APIDOC ## Quick Start ```python theme={null} import asyncio from ctxprotocol import ContextClient async def main(): async with ContextClient(api_key="sk_live_...") as client: answer = await client.query.run( query="What are the top whale movements on Base?", response_shape="answer_with_evidence", ) print(answer.response) print(answer.summary) print(answer.evidence.facts if answer.evidence else None) asyncio.run(main()) ``` ``` -------------------------------- ### Quick Start: Query the API Source: https://docs.ctxprotocol.com/sdk/python-reference A basic example demonstrating how to initialize the ContextClient and run a query. Ensure you have set up your API key and completed prerequisites. ```python import asyncio from ctxprotocol import ContextClient async def main(): async with ContextClient(api_key="sk_live_...") as client: answer = await client.query.run( query="What are the top whale movements on Base?", response_shape="answer_with_evidence", ) print(answer.response) print(answer.summary) print(answer.evidence.facts if answer.evidence else None) asyncio.run(main()) ``` -------------------------------- ### Quick Start with ContextClient Source: https://docs.ctxprotocol.com/sdk/reference Initialize the ContextClient and run a query. This example demonstrates basic usage for fetching information. ```typescript 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); ``` -------------------------------- ### Execute Mode Client Quick Start Source: https://docs.ctxprotocol.com/sdk/python-reference Demonstrates how to use the Execute mode of the SDK to discover and execute a tool. Ensure you have an API key and have installed the SDK. This example shows basic session management and tool execution. ```python import asyncio from ctxprotocol import ContextClient async def main(): async with ContextClient(api_key="sk_live_...") as client: tools = await client.discovery.search( "gas prices", mode="execute", surface="execute", require_execute_pricing=True, ) session = await client.tools.start_session(max_spend_usd="1.00") method = tools[0].mcp_tools[0] result = await client.tools.execute( tool_id=tools[0].id, tool_name=method.name, args={"chainId": 1}, session_id=session.session.session_id, ) print(result.result) print(result.session) # method_price, spent, remaining, max_spend, ... asyncio.run(main()) ``` -------------------------------- ### Install @ctxprotocol/sdk with npm Source: https://docs.ctxprotocol.com/sdk/reference Install the SDK using npm. ```bash npm install @ctxprotocol/sdk ``` -------------------------------- ### Install @ctxprotocol/sdk with yarn Source: https://docs.ctxprotocol.com/sdk/reference Install the SDK using yarn. ```bash yarn add @ctxprotocol/sdk ``` -------------------------------- ### Installing Dependencies Source: https://docs.ctxprotocol.com/guides/troubleshooting Install project dependencies using pnpm or npm. This is crucial for the server to start correctly. ```bash pnpm install # or npm install ``` -------------------------------- ### Start Development Server Source: https://docs.ctxprotocol.com/guides/quickstart Command to start the development server using pnpm. ```bash pnpm dev ``` -------------------------------- ### Agent Routine Example (TypeScript) Source: https://docs.ctxprotocol.com/sdk/agent-routines This example demonstrates how to build an agent routine using the `ctxprotocol` SDK in TypeScript. It covers setting up the API key, defining the query, and processing the routine's response. Install the `ctxprotocol-routine-builder` skill and run with `npm run routine` after setting `CONTEXT_API_KEY`. ```typescript import { Context } from "@ctxprotocol/context"; const context = new Context(process.env.CONTEXT_API_KEY as string); async function routine() { const routine = await context.agent.routine( "What are the top 5 trending crypto assets by market cap in the last 24 hours?", { evidence_only: true, includeDataUrl: true, } ); console.log(routine); } routine(); ``` -------------------------------- ### Install Context SDK for Python Source: https://docs.ctxprotocol.com/guides/buyer-quickstart Install the Context SDK using uv. This is required before running Python queries. ```bash uv add ctxprotocol ``` -------------------------------- ### Install SDK Packages Source: https://docs.ctxprotocol.com/grants Install the necessary SDK packages for building your MCP server. Ensure you have Node.js and npm installed. ```bash npm install @ctxprotocol/sdk @modelcontextprotocol/sdk ``` -------------------------------- ### Example Prompt for AI Agent (CoinGecko API) Source: https://docs.ctxprotocol.com/guides/build-tools An example prompt to guide an AI agent in building an MCP server for the Context Marketplace using the CoinGecko API and the mcp-builder-template.md. ```plaintext I want to build an MCP server for the Context Marketplace using the CoinGecko API. 1. Use context7 to fetch the CoinGecko API documentation 2. Follow the mcp-builder-template.md workflow: - PHASE 1: Discover all endpoints - PHASE 2: Generate the product contract: target user, 5 must-win prompts, evidence fields, and ideal output surface (STOP for my review) - PHASE 3: Design and implement tools after I approve Focus on a premium feature users would actually pay for, not a generic API wrapper. The end result should either power Query answers with evidence or provide Execute primitives with a clean normalized schema. ``` -------------------------------- ### Install the ctxprotocol SDK Source: https://docs.ctxprotocol.com/guides/handshake-architecture Install the Python SDK using pip. This is the first step to using Handshake features in your Python project. ```bash pip install ctxprotocol ``` -------------------------------- ### Initialize Context Client and Run a Query (TypeScript) Source: https://docs.ctxprotocol.com/ Installs the SDK and initializes the ContextClient with an API key. Use this to query for information or trigger agent actions. ```typescript import { ContextClient } from "@ctxprotocol/sdk"; const client = new ContextClient({ apiKey: "sk_live_..." }); const answer = await client.query.run("What are the top whale movements on Base?"); console.log(answer.response); ``` -------------------------------- ### Complete Example: Hyperliquid Order Tool Source: https://docs.ctxprotocol.com/guides/handshake-architecture A comprehensive example demonstrating how to build an order tool using the TypeScript SDK, including creating signature requests for placing orders. ```typescript import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { createSignatureRequest, wrapHandshakeResponse, createContextMiddleware, } from "@ctxprotocol/sdk"; const TOOLS = [ { name: "place_order", description: "Place a perpetual order on Hyperliquid", inputSchema: { type: "object", properties: { coin: { type: "string", description: "e.g., ETH, BTC" }, isBuy: { type: "boolean" }, size: { type: "number" }, price: { type: "number" }, }, required: ["coin", "isBuy", "size", "price"], }, outputSchema: { type: "object", properties: { status: { type: "string" }, message: { type: "string" }, _meta: { type: "object" }, }, }, _meta: { contextRequirements: ["hyperliquid"], // Inject user's portfolio }, }, ]; server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === "place_order") { const { coin, isBuy, size, price } = request.params.arguments; // Get asset index from market metadata const assetIndex = await getAssetIndex(coin); const signatureRequest = createSignatureRequest({ domain: { name: "HyperliquidSignTransaction", version: "1", chainId: 42161, }, types: { Order: [ { name: "asset", type: "uint32" }, { name: "isBuy", type: "bool" }, { name: "limitPx", type: "uint64" }, { name: "sz", type: "uint64" }, { name: "reduceOnly", type: "bool" }, ], }, primaryType: "Order", message: { asset: assetIndex, isBuy, limitPx: Math.round(price * 1e8), sz: Math.round(size * 1e8), reduceOnly: false, }, meta: { description: `${isBuy ? "Buy" : "Sell"} ${size} ${coin} at $${price}`, protocol: "Hyperliquid", action: isBuy ? "Long" : "Short", tokenSymbol: coin, tokenAmount: size.toString(), warningLevel: size * price > 10000 ? "caution" : "info", }, callbackToolName: "submit_signed_order", }); return wrapHandshakeResponse(signatureRequest); } }); ``` -------------------------------- ### Example Tool Definition with Input Schema Source: https://docs.ctxprotocol.com/sdk/python-reference Provides an example of a tool definition ('get_price_history') including a detailed JSON schema for its input parameters. This demonstrates how to specify types, defaults, and examples for tool arguments. ```python 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": [], }, }] ``` -------------------------------- ### Install Server Dependencies Source: https://docs.ctxprotocol.com/guides/build-tools Install the necessary SDKs and development tools for building an MCP server. This includes the core SDKs and type definitions for Express. ```bash pnpm add @modelcontextprotocol/sdk express pnpm add @ctxprotocol/sdk pnpm add -D @types/express ``` -------------------------------- ### Install ctxprotocol with FastAPI support Source: https://docs.ctxprotocol.com/sdk/python-reference Install the ctxprotocol Python package with optional FastAPI support. ```bash pip install ctxprotocol[fastapi] ``` -------------------------------- ### Install Context SDK for TypeScript Source: https://docs.ctxprotocol.com/guides/buyer-quickstart Install the Context SDK using pnpm. This is required before running TypeScript queries. ```bash pnpm add @ctxprotocol/sdk ``` -------------------------------- ### Create and Initialize Project Source: https://docs.ctxprotocol.com/guides/quickstart Set up a new project directory, initialize it with pnpm, and install necessary dependencies for an MCP server. This includes SDKs, Express, dotenv, and TypeScript for development. ```bash # Create project directory mkdir my-first-mcp cd my-first-mcp # Initialize the project pnpm init # Install dependencies pnpm add @modelcontextprotocol/sdk @ctxprotocol/sdk express dotenv pnpm add -D typescript @types/node @types/express tsx ``` -------------------------------- ### Complete MCP Server Example Source: https://docs.ctxprotocol.com/guides/build-tools A full working example of an MCP server using express, defining tools, and handling requests for query and call operations. ```typescript import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; import express from "express"; import { createContextMiddleware } from "@ctxprotocol/sdk"; const app = express(); app.use(express.json()); app.use("/mcp", createContextMiddleware()); const TOOLS = [{ name: "get_gas_price", description: "Get current gas prices", inputSchema: { type: "object", properties: { chainId: { type: "number", description: "EVM chain ID", default: 1, examples: [1, 10, 8453], }, }, }, outputSchema: { type: "object", properties: { gasPrice: { type: "number" }, unit: { type: "string" }, }, required: ["gasPrice", "unit"], }, }]; const server = new Server( { name: "my-gas-tool", version: "1.0.0" }, { capabilities: { tools: {} } } ); server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS, })); server.setRequestHandler(CallToolRequestSchema, async (request) => { const data = await fetchGasData(request.params.arguments.chainId); return { content: [{ type: "text", text: JSON.stringify(data) }], structuredContent: data, }; }); app.listen(3000, () => { console.log("MCP server running on port 3000"); }); ``` -------------------------------- ### Install ctxprotocol using Poetry Source: https://docs.ctxprotocol.com/sdk/python-reference Add the ctxprotocol Python package to your project using Poetry. ```bash poetry add ctxprotocol ``` -------------------------------- ### Execute Mode Quick Start Source: https://docs.ctxprotocol.com/sdk/reference Demonstrates how to discover and execute a tool in 'execute' mode. Ensure 'requireExecutePricing' is true for discoverability in this mode. A session is initiated with a spending limit. ```typescript 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... ``` -------------------------------- ### Start MCP Server Source: https://docs.ctxprotocol.com/guides/quickstart Starts the MCP server on a specified port, logging server information to the console. ```typescript // Start server const PORT = Number(process.env.PORT || 3000); app.listen(PORT, () => { console.log(`My First MCP Server running on http://localhost:${PORT}`); console.log(`MCP endpoint: http://localhost:${PORT}/mcp`); console.log(`Health check: http://localhost:${PORT}/health`); }); ``` -------------------------------- ### Run a Simple Query Source: https://docs.ctxprotocol.com/sdk/reference Execute a natural-language query using the SDK. This basic example shows how to retrieve the answer and tool usage. ```typescript const answer = await client.query.run("What are the top whale movements on Base?"); console.log(answer.response); console.log(answer.toolsUsed); console.log(answer.cost); // `orchestrationMetrics` and `developerTrace` are only populated when // `includeDeveloperTrace: true` is passed — see the next example. ``` -------------------------------- ### Tool Configuration Example Source: https://docs.ctxprotocol.com/sdk/reference An example of defining a 'TOOLS' array, where each element represents a tool with its name and input schema. This configuration is used to register tools with the protocol. ```typescript 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: [], }, }]; ``` -------------------------------- ### Query API Example Source: https://docs.ctxprotocol.com/sdk/reference This example demonstrates how to use the client.query.run method to fetch data with a specified response shape and access various fields from the result envelope. ```APIDOC ## client.query.run ### Description Executes a query against the Context Protocol and returns structured results based on the specified `responseShape`. ### Method `query.run(options: { query: string, responseShape?: 'answer_with_evidence' | 'evidence_only' }): Promise ### Parameters #### Query Parameters - **query** (string) - Required - The natural language query to execute. - **responseShape** (string) - Optional - Determines the structure of the response. Can be 'answer_with_evidence' (default) or 'evidence_only'. ### Request Example ```typescript 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", }); ``` ### Response #### Success Response The response structure depends on the `responseShape`. **Common Envelope Fields:** - **summary** (string) - Short machine-friendly summary of the answer. - **evidence** (object) - Canonical facts, source refs, assumptions, known unknowns, retrieval reason codes, and optional wedge-specific `marketIntelligence`. - **evidence.sourceRefs** (array) - References to the sources used. - **evidence.marketIntelligence** (object) - Market intelligence data, potentially including `venueBreakdown`. - **evidence.marketIntelligence.venueBreakdown** (object) - Breakdown by venue. - **artifacts** (object) - Contains `dataUrl`, canonical dataset metadata, and stage-artifact kinds. - **view** (object) - Optional UI/render hint such as `table`, `leaderboard`, `heatmap`, or `timeseries`, plus optional `metrics`, `columns`, and `rows`. - **outcome** (object) - Public outcome label, tone, `stopReason`, and optional `issueClass`. - **outcome.stopReason** (string) - Reason the query stopped. - **outcome.issueClass** (string) - Classification of the issue. - **controller** (object) - Public bounded-controller summary including `actionsTaken`, `nextAction`, and patch-preservation flags. - **controller.actionsTaken** (array) - List of actions taken. - **freshness** (object) - `asOf` timestamp and freshness note. - **confidence** (object) - Confidence level, reason, fact counts, and gap signals. - **usage** (object) - Duration, cost, tools used, outcome type, and optional orchestration metrics. - **usage.toolsUsed** (array) - List of tools used. #### Response Example ```json { "response": "machine-friendly summary for evidence_only", "summary": "...", "evidence": { "sourceRefs": [...], "marketIntelligence": { "venueBreakdown": {...} } }, "artifacts": {...}, "view": {...}, "outcome": { "stopReason": "...", "issueClass": "..." }, "controller": { "actionsTaken": [...] }, "freshness": {...}, "confidence": {...}, "usage": { "toolsUsed": [...] } } ``` ``` -------------------------------- ### Detailed Output Schema Example Source: https://docs.ctxprotocol.com/guides/build-tools Demonstrates a well-defined output schema with exact property names and descriptions for optimal runtime interpretation. ```typescript // ✅ Good: Detailed schema with exact property names and descriptions outputSchema: { type: "object", properties: { data: { type: "array", description: "Array of exchange balance objects, one per exchange", items: { type: "object", properties: { exchange_name: { type: "string", description: "Exchange name (e.g. 'Binance')" }, total_balance: { type: "number", description: "Total balance in the queried coin" }, balance_change_1d: { type: "number", description: "Balance change in last 24 hours" }, balance_change_percent_1d: { type: "number", description: "Percent change in last 24 hours" }, } } }, fetchedAt: { type: "string", description: "ISO 8601 timestamp" } } } ``` -------------------------------- ### Start and Poll Async Query Jobs Source: https://docs.ctxprotocol.com/sdk/python-reference Illustrates how to initiate an asynchronous query job for complex requests that might exceed single-request timeouts. It covers starting a job, checking its status, and polling for completion, including retrieving the final result. ```python job = await client.query.start( query="Build a chart-ready dataset of Base whale movements over the last 30 days", response_shape="evidence_only", include_data_url=True, ) status = await client.query.get_status(job.job_id) print(status.status) # queued | running | completed | failed completed = await client.query.poll( job.job_id, interval_ms=2000, timeout_ms=15 * 60_000, ) print(completed.result) ``` -------------------------------- ### Start an Execute Session with Budget Source: https://docs.ctxprotocol.com/sdk/reference Initiates a new session for executing tool methods, defining a maximum amount that can be spent in USD for that session. ```typescript const started = await client.tools.startSession({ maxSpendUsd: "5.00" }); console.log(started.session.sessionId); console.log(started.session.maxSpend); ``` -------------------------------- ### client.tools.start_session Source: https://docs.ctxprotocol.com/sdk/python-reference Start an execute session budget envelope. This method initiates a session that can encompass multiple tool executions, allowing for a defined budget to be set for the entire session. ```APIDOC ## client.tools.start_session(max_spend_usd) ### Description Start an execute session budget envelope. ### Parameters #### Query Parameters - **max_spend_usd** (str) - Required - The maximum amount to spend in USD for this session. ``` -------------------------------- ### Schema Compliance Example Source: https://docs.ctxprotocol.com/guides/build-tools Demonstrates correct and incorrect schema compliance for tool outputs. Ensure your output matches the declared schema to avoid disputes. ```typescript // ❌ BAD: Schema says number, but you return string outputSchema: { temperature: { type: "number" } } structuredContent: { temperature: "72" } // GUILTY - schema mismatch! // ✅ GOOD: Output matches schema exactly outputSchema: { temperature: { type: "number" } } structuredContent: { temperature: 72 } // Valid ``` -------------------------------- ### Run, Resume, and Fork Queries Source: https://docs.ctxprotocol.com/sdk/python-reference Demonstrates how to run an initial query, obtain a session handle, and then resume or fork from that session for subsequent queries. Use `resume_from` to continue a previous attempt or `fork_from` to branch while preserving lineage. ```python first = await client.query.run( query="Find the biggest Base whale movements today", include_developer_trace=True, ) handle = first.query_session if handle: resumed = await client.query.run( query="Focus only on wallets with exchange interactions", resume_from={ "sessionId": handle.session_id, "attemptId": handle.attempt_id, }, ) forked = await client.query.run( query="Try the same question with stricter evidence requirements", fork_from={ "sessionId": handle.session_id, "attemptId": handle.attempt_id, "reason": "manual_fork", }, ) print(resumed.response) print(forked.response) ``` -------------------------------- ### Initialize Git and Create Repository Source: https://docs.ctxprotocol.com/guides/quickstart Initialize a new Git repository, stage all files, commit them, and create a new public GitHub repository, pushing the initial commit. ```bash git init git add . git commit -m "Initial commit" gh repo create my-first-mcp --public --push ``` -------------------------------- ### Initialize ContextClient for Production and Local Development Source: https://docs.ctxprotocol.com/sdk/reference Demonstrates how to instantiate the ContextClient. Use environment variables for API keys in production and hardcoded values with a custom baseUrl for local development. ```typescript // Production const client = new ContextClient({ apiKey: process.env.CONTEXT_API_KEY!, }); // Local development const client = new ContextClient({ apiKey: "sk_test_...", baseUrl: "http://localhost:3000", }); ``` -------------------------------- ### client.tools.startSession Source: https://docs.ctxprotocol.com/sdk/reference Initiates an execution session with a specified budget. ```APIDOC ## client.tools.startSession({ maxSpendUsd }) ### Description Start an execute session budget envelope. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * **maxSpendUsd** (string) - Required - The maximum amount to spend in USD for this session. ### Request Example ```typescript const started = await client.tools.startSession({ maxSpendUsd: "5.00" }); console.log(started.session.sessionId); console.log(started.session.maxSpend); ``` ### Response #### Success Response (200) * **session** (object) - Contains session details including `sessionId` and `maxSpend`. #### Response Example { "session": { "sessionId": "sess_abc123", "maxSpend": "5.00" } } ``` -------------------------------- ### Initialize ContextClient Source: https://docs.ctxprotocol.com/sdk/python-reference Instantiate the ContextClient for production using an environment variable for the API key. For local development, provide the API key and base URL directly. Always use the `async with` context manager or call `await client.close()` to release resources. ```python import os from ctxprotocol import ContextClient # Production client = ContextClient(api_key=os.environ["CONTEXT_API_KEY"]) # Local development client = ContextClient( api_key="sk_test_...", base_url="http://localhost:3000", ) ``` -------------------------------- ### Handling Long-Running Analyses in Build Tools Source: https://docs.ctxprotocol.com/guides/build-tools Illustrates how to structure methods for long-running analyses. The 'BAD' example shows a method that times out, while the 'GOOD' examples demonstrate pre-computation for Query mode and focused methods for Execute mode. ```typescript // ❌ BAD (either mode): Long-running analysis at request time { name: "analyze_all_wallets", returns: "timeout after 60s" } // ✅ GOOD (Query): Pre-computed results served instantly { name: "get_smart_money_wallets", returns: "instant curated insight from your DB" } // ✅ GOOD (Execute): Focused method the agent calls per-wallet { name: "get_wallet_activity", inputs: "{ address, timeRange }", returns: "normalized activity data" } ``` -------------------------------- ### Define Tool with Input and Output Schemas Source: https://docs.ctxprotocol.com/guides/build-tools Example of defining a tool with input and output schemas, including default values and examples for input arguments. This structure helps the AI generate arguments and select the correct method. ```typescript const TOOLS = [{ name: "get_gas_price", description: "Get current gas prices for any EVM chain", inputSchema: { type: "object", properties: { chainId: { type: "number", description: "EVM chain ID", default: 1, examples: [1, 10, 8453], }, }, }, outputSchema: { type: "object", properties: { gasPrice: { type: "number" }, unit: { type: "string" }, }, required: ["gasPrice", "unit"], }, }]; return { content: [{ type: "text", text: JSON.stringify(data) }], structuredContent: data, }; ``` -------------------------------- ### context_query Source: https://docs.ctxprotocol.com/sdk/mcp Ask a natural-language question and get a grounded answer powered by the full marketplace. ```APIDOC ## context_query ### Description Ask a natural-language question and get a grounded answer powered by the full marketplace. ### Method POST ### Endpoint /context_query ### Parameters #### Request Body - **question** (string) - Required - The question to answer (1–4000 chars) - **agentModelId** (string) - Optional - Advanced: choose the main librarian agent model for the merged execution/final-response loop - **responseShape** (string) - Optional - `answer_with_evidence` (default) or `evidence_only`. See [Answer vs evidence](#answer-vs-evidence) - **toolIds** (string[]) - Optional - Restrict query to specific tool UUIDs (Manual Mode). Omit for Auto Mode discovery and selection - **favoritesOnly** (boolean) - Optional - Override the account-level Favorites-Only Auto Mode for this request - **includeData** (boolean) - Optional - Include bounded execution data inline. Large payloads return a preview plus full-data references - **includeDataUrl** (boolean) - Optional - Persist the full execution data and return a URL, keeping large payloads out of your context window. Defaults to true in the ctxprotocol MCP tool - **includeDeveloperTrace** (boolean) - Optional - Include a machine-readable runtime trace (tool selection, retries, loops) for debugging ### Request Example ```json { "question": "What are the top Polymarket markets by volume right now?" } ``` ### Response #### Success Response (200) - **answer** (string) - The answer to the question. - **evidence** (object[]) - Structured evidence supporting the answer. - **metadata** (object) - Metadata about the query execution. - **jobId** (string) - Optional - Returned for long jobs, poll `context_query_status` with this ID. #### Response Example ```json { "answer": "The top Polymarket markets by volume are...", "evidence": [ { "text": "Market X has a volume of $1M.", "source": "polymarket.com" } ], "metadata": { "agentModelId": "kimi-k2.6-model" } } ``` ``` -------------------------------- ### Search for Tools using String Query or Options Object Source: https://docs.ctxprotocol.com/sdk/reference Shows how to search for tools. The first example uses a simple query string and an optional limit. The second demonstrates a more complex search using an options object with specific filters like mode and surface. ```typescript 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, }); ``` -------------------------------- ### Python Tool Metadata with Pricing Source: https://docs.ctxprotocol.com/guides/tool-metadata Example of defining tool metadata in Python, including the `_meta.pricing.executeUsd` field for setting execution price. ```python TOOLS = [ { "name": "get_gas_prices", "description": "Get current gas prices for EVM chains", "_meta": { "surface": "both", "queryEligible": True, "latencyClass": "instant", "pricing": { "executeUsd": "0.001", }, }, "inputSchema": { "type": "object", "properties": { "chainId": {"type": "number", "description": "EVM chain ID"}, }, }, "outputSchema": { "type": "object", "properties": { "gasPrice": {"type": "number"}, "unit": {"type": "string"}, }, "required": ["gasPrice", "unit"], }, }, ] ``` -------------------------------- ### Running Queries with Resume and Fork Source: https://docs.ctxprotocol.com/sdk/python-reference Demonstrates how to run a query and then resume or fork from its session to continue or branch the query process. ```APIDOC ## Running Queries with Resume and Fork Every Query response can include `query_session` handles. Use `resume_from` to continue from a previous attempt, or `fork_from` to branch from an attempt while preserving lineage. ```python first = await client.query.run( query="Find the biggest Base whale movements today", include_developer_trace=True, ) handle = first.query_session if handle: resumed = await client.query.run( query="Focus only on wallets with exchange interactions", resume_from={ "sessionId": handle.session_id, "attemptId": handle.attempt_id, }, ) forked = await client.query.run( query="Try the same question with stricter evidence requirements", fork_from={ "sessionId": handle.session_id, "attemptId": handle.attempt_id, "reason": "manual_fork", }, ) print(resumed.response) print(forked.response) ``` ``` -------------------------------- ### TypeScript Tool Metadata with Pricing Source: https://docs.ctxprotocol.com/guides/tool-metadata Example of defining tool metadata in TypeScript, including the `_meta.pricing.executeUsd` field for setting execution price. ```typescript const TOOLS = [ { name: "get_gas_prices", description: "Get current gas prices for EVM chains", _meta: { surface: "both", queryEligible: true, latencyClass: "instant", pricing: { executeUsd: "0.001", }, }, inputSchema: { type: "object", properties: { chainId: { type: "number", description: "EVM chain ID" }, }, }, outputSchema: { type: "object", properties: { gasPrice: { type: "number" }, unit: { type: "string" }, }, required: ["gasPrice", "unit"], }, }, { name: "stream_live_trades", description: "Stream real-time trade data (Execute only)", _meta: { surface: "execute", queryEligible: false, latencyClass: "streaming", pricing: { executeUsd: "0.0005", }, }, inputSchema: { type: "object", properties: {} }, outputSchema: { type: "object", properties: {} }, }, ]; ``` -------------------------------- ### Run First Buyer Query with Python SDK Source: https://docs.ctxprotocol.com/guides/buyer-quickstart Execute a paid query using the Context SDK in Python. Ensure your API key is set as an environment variable. This snippet demonstrates fetching answers with evidence and data URLs asynchronously. ```python import asyncio import os from ctxprotocol import ContextClient async def main(): async with ContextClient(api_key=os.environ["CONTEXT_API_KEY"]) as client: answer = await client.query.run( query="What are the top whale movements on Base today?", response_shape="answer_with_evidence", include_data_url=True, ) print(answer.response) print(answer.evidence.facts if answer.evidence else None) print(answer.cost) asyncio.run(main()) ``` -------------------------------- ### Set up MCP Server and Request Handlers Source: https://docs.ctxprotocol.com/guides/quickstart Initialize the MCP server and define handlers for listing tools and calling tools. The `get_random_quote` tool logic is implemented here. ```typescript // ============================================================================ // MCP SERVER SETUP // ============================================================================ const server = new Server( { name: "my-first-mcp", version: "1.0.0" }, { capabilities: { tools: {} } } ); // Handle tools/list - returns tool definitions server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS, })); // Handle tools/call - executes tool and returns result server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name } = request.params; if (name === "get_random_quote") { const randomIndex = Math.floor(Math.random() * QUOTES.length); const selected = QUOTES[randomIndex]; const result = { quote: selected.quote, author: selected.author, fetchedAt: new Date().toISOString(), }; return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }], structuredContent: result, // REQUIRED by Context }; } return { content: [{ type: "text", text: `Unknown tool: ${name}` }], isError: true, }; }); ``` -------------------------------- ### TypeScript Agent Routine Starter Source: https://docs.ctxprotocol.com/sdk/mcp-skill A runnable TypeScript starter for adapting the agent routine from the Context SDK repository. ```typescript import { Context } from "@ctxprotocol/sdk"; const context = new Context(); async function runAgentRoutine() { // Example: Query for an answer with evidence const queryResult = await context.query( "What are the top 5 selling products in the last quarter?", { responseShape: "answer_with_evidence" } // Default, can be omitted ); console.log("Query Result:", JSON.stringify(queryResult, null, 2)); // Example: Query for evidence only, including data URL const evidenceOnlyResult = await context.query( "List all transactions for customer ID 12345.", { responseShape: "evidence_only", includeDataUrl: true } ); console.log("Evidence Only Result:", JSON.stringify(evidenceOnlyResult, null, 2)); // Example: Discover and execute a specific tool const discoverResult = await context.discover({ mode: "execute" }); if (discoverResult.tools && discoverResult.tools.length > 0) { const toolToExecute = discoverResult.tools[0]; console.log("Discovered Tool:", toolToExecute); // Assuming the tool requires arguments, you'd pass them here. // The exact arguments depend on the tool's schema. // For demonstration, we'll pass an empty object. const executeResult = await context.execute({ toolId: toolToExecute.id, args: {} }); console.log("Execute Result:", JSON.stringify(executeResult, null, 2)); } else { console.log("No executable tools found."); } // Example: Pinning tools for a repeatable query const pinnedToolsResult = await context.query( "What is the current market sentiment?", { toolIds: ["tool-id-1", "tool-id-2"] } // Replace with actual tool IDs ); console.log("Pinned Tools Result:", JSON.stringify(pinnedToolsResult, null, 2)); } runAgentRoutine().catch(console.error); ``` -------------------------------- ### Declare Context Requirements (Python) Source: https://docs.ctxprotocol.com/guides/tool-metadata Define context requirements in Python by including `_meta.contextRequirements` in your `Tool` definition. This example specifies the need for 'hyperliquid' data. ```python from mcp.server import Server from mcp.types import Tool tools = [ Tool( name="analyze_my_positions", description="Analyze user's Hyperliquid perpetual positions", inputSchema={ "type": "object", "properties": { "portfolio": { "type": "object", "description": "User's Hyperliquid portfolio (injected by platform)", }, }, "required": ["portfolio"], }, _meta={ "contextRequirements": ["hyperliquid"], }, ), ] ```