### Install and Start the Server Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/normalized-data-provider/README.md Use these commands to install dependencies and start the normalized data provider server. ```bash pnpm install pnpm start ``` -------------------------------- ### Quick Start Example Source: https://github.com/ctxprotocol/sdk/blob/main/README.md A combined quick start example demonstrating both Query and Execute modes within the Context SDK. ```APIDOC ## Quick Start ### Description This section provides a quick start guide demonstrating how to initialize the Context SDK client and use both the 'Query' and 'Execute' modes. ### Code Example ```typescript import { ContextClient } from "@ctxprotocol/sdk"; const client = new ContextClient({ apiKey: "sk_live_...", }); // Pay-per-response: Ask a question, get a managed answer package const answer = await client.query.run({ query: "What are the top whale movements on Base?", responseShape: "answer_with_evidence", }); console.log(answer.response); // Execute surface: require explicit execute pricing const tools = await client.discovery.search({ query: "gas prices", mode: "execute", surface: "execute", requireExecutePricing: true, }); const session = await client.tools.startSession({ maxSpendUsd: "1.00" }); const result = await client.tools.execute({ toolId: tools[0].id, toolName: tools[0].mcpTools[0].name, args: { chainId: 1 }, sessionId: session.session.sessionId ?? undefined, }); console.log(result.result); ``` ``` -------------------------------- ### Install Dependencies and Start Server Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/coinglass-contributor/README.md Install project dependencies using pnpm install and then start the server with pnpm dev. Ensure you have Node.js and pnpm installed. ```bash pnpm install pnpm dev ``` -------------------------------- ### Install Dependencies and Start Server Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/binance-contributor/README.md Commands to install project dependencies, start the development server, or build and run the application. ```bash pnpm install pnpm dev # Or build and run pnpm build pnpm start ``` -------------------------------- ### Run Examples Source: https://github.com/ctxprotocol/sdk/blob/main/examples/client/README.md Execute the provided examples using pnpm. The commands 'query', 'execute', and 'start' correspond to different example files. ```bash pnpm run query ``` ```bash pnpm run execute ``` ```bash pnpm start ``` -------------------------------- ### Setup Exa AI MCP Server Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/exa-contributor/README.md Steps to set up the Exa AI MCP Server, including copying the environment file, installing dependencies, and starting the development server. Ensure your EXA_API_KEY is added to the .env file. ```bash cd examples/server/exa-contributor cp env.example .env # add your EXA_API_KEY from https://dashboard.exa.ai/api-keys pnpm install pnpm run dev ``` -------------------------------- ### Install Dependencies Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/README.md Install the necessary Node.js dependencies for the Kalshi contributor example. ```bash cd examples/server/kalshi-contributor npm install ``` -------------------------------- ### Install @ctxprotocol/sdk Source: https://context7.com/ctxprotocol/sdk/llms.txt Install the SDK using npm, pnpm, or yarn. ```bash npm install @ctxprotocol/sdk # or pnpm add @ctxprotocol/sdk # or yarn add @ctxprotocol/sdk ``` -------------------------------- ### Server Setup and Run Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/blocknative-contributor/README.md Instructions for setting up the Blocknative Gas MCP Server. This includes copying the environment file, installing dependencies, and running the development server. Ensure you add your BLOCKNATIVE_API_KEY to the `.env` file. ```bash cd examples/server/blocknative-contributor cp env.example .env # add BLOCKNATIVE_API_KEY pnpm install pnpm run dev ``` -------------------------------- ### Start Development Server Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/polymarket-contributor/README.md Instructions for starting the development server using pnpm. ```bash cp env.example .env pnpm dev ``` -------------------------------- ### Setup Hummingbot Server Environment Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/hummingbot-contributor/README.md Sets up the Hummingbot server environment on the remote machine, including starting the server with PM2. This script should be run on the server. ```bash ./setup-hummingbot-server.sh ``` -------------------------------- ### Install @ctxprotocol/sdk with yarn Source: https://github.com/ctxprotocol/sdk/blob/main/README.md Use this command to install the SDK using yarn. ```bash yarn add @ctxprotocol/sdk ``` -------------------------------- ### Install @ctxprotocol/sdk with npm Source: https://github.com/ctxprotocol/sdk/blob/main/README.md Use this command to install the SDK using npm. ```bash npm install @ctxprotocol/sdk ``` -------------------------------- ### Install @ctxprotocol/sdk with pnpm Source: https://github.com/ctxprotocol/sdk/blob/main/README.md Use this command to install the SDK using pnpm. ```bash pnpm add @ctxprotocol/sdk ``` -------------------------------- ### Execute Mode Example Source: https://github.com/ctxprotocol/sdk/blob/main/README.md Demonstrates how to use the 'execute' mode for deterministic pipelines. This involves starting a session, discovering tools, and executing a specific tool with defined arguments. ```APIDOC ## Execute Mode ### Description This mode provides raw data and full control with explicit method pricing and session budgets. It is suitable for deterministic pipelines, raw outputs, and explicit spend envelopes. ### Method `client.tools.execute()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **toolId** (string) - Required - The ID of the tool to execute. - **toolName** (string) - Required - The name of the tool to execute. - **args** (object) - Required - Arguments for the tool execution. - **sessionId** (string) - Optional - The ID of the session to use for execution. ### Request Example ```typescript const session = await client.tools.startSession({ maxSpendUsd: "2.00" }); const executeTools = await client.discovery.search({ query: "whale transactions", mode: "execute", surface: "execute", requireExecutePricing: true, }); const result = await client.tools.execute({ toolId: executeTools[0].id, toolName: executeTools[0].mcpTools[0].name, args: { chain: "base", limit: 20 }, sessionId: session.session.sessionId ?? undefined, }); console.log(result.session); // methodPrice, spent, remaining, maxSpend, ... ``` ### Response #### Success Response (200) - **session** (object) - Contains pricing and budget information for the session. ``` -------------------------------- ### Get Trades Example - Python SDK Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Demonstrates how to retrieve trade data using the Kalshi Python SDK. Requires the kalshi_python library. ```python import kalshi_python from kalshi_python.models.get_trades_response import GetTradesResponse from kalshi_python.rest import ApiException from pprint import pprint # Defining the host is optional and defaults to https://api.elections.kalshi.com/trade-api/v2 ``` -------------------------------- ### Install Required Dependencies Source: https://github.com/ctxprotocol/sdk/blob/main/docs/mcp-builder-template.md Installs the necessary SDKs and development tools for building an MCP server. ```bash npm install @modelcontextprotocol/sdk @ctxprotocol/sdk express npm install -D @types/express typescript ``` -------------------------------- ### Install MCP SDK for Python (Marketplace SDK Testing) Source: https://github.com/ctxprotocol/sdk/blob/main/docs/mcp-contributor-deep-validation-system-prompt.md Use this command to install the SDK for marketplace SDK testing with Python. ```bash # For marketplace SDK testing (post-submission) pip install ctxprotocol ``` -------------------------------- ### Server Dependencies Installation Source: https://github.com/ctxprotocol/sdk/blob/main/README.md Install the necessary server dependencies using pnpm. This includes the SDK, express, and its types. ```bash pnpm add @modelcontextprotocol/sdk express pnpm add -D @types/express ``` -------------------------------- ### Install MCP SDK for TypeScript (Marketplace SDK Testing) Source: https://github.com/ctxprotocol/sdk/blob/main/docs/mcp-contributor-deep-validation-system-prompt.md Use this command to install the SDK for marketplace SDK testing after submission. ```bash # For marketplace SDK testing (post-submission) npm install @ctxprotocol/sdk ``` -------------------------------- ### Install Kalshi Python SDK (Async) Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Use pip to install the package for asynchronous operations with the Kalshi Python SDK. ```bash pip install kalshi_python_async ``` -------------------------------- ### Install Kalshi Python SDK (Sync) Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Use pip to install the package for synchronous operations with the Kalshi Python SDK. ```bash pip install kalshi_python_sync ``` -------------------------------- ### Update Subscription - Add Markets Example Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Example of adding specified markets to an existing subscription channel. The 'action' parameter should be 'add_markets'. ```json { "id": 124, "cmd": "update_subscription", "params": { "sids": [456], "market_tickers": ["NEW-MARKET-1", "NEW-MARKET-2"], "action": "add_markets" } } ``` -------------------------------- ### Subscribe to Channels Example Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Example of a request to subscribe to market data channels. Ensure 'channels' and 'market_ticker' are correctly specified. ```json { "id": 1, "cmd": "subscribe", "params": { "channels": ["ticker"], "market_ticker": "KXBTCD-25AUG0517-T114999.99" } } ``` -------------------------------- ### Full Agentic Loop Example Source: https://github.com/ctxprotocol/sdk/blob/main/README.md An example demonstrating the full agentic loop, from discovery to LLM synthesis. ```APIDOC ## Full Agentic Loop Example ### Description This example demonstrates a complete agent loop using the Context SDK, including discovering tools, constructing a system prompt for an LLM, executing a tool based on the LLM's decision, and synthesizing a final answer. ### Method Signature ```typescript agentLoop(userQuery: string) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { ContextClient, ContextError } from "@ctxprotocol/sdk"; const client = new ContextClient({ apiKey: process.env.CONTEXT_API_KEY! }); async function agentLoop(userQuery: string) { // 1. Discover relevant tools const tools = await client.discovery.search(userQuery); if (tools.length === 0) { return "I couldn't find any tools to help with that."; } // 2. Build the system prompt with schemas const toolDescriptions = tools.slice(0, 5).map(t => ({ id: t.id, name: t.name, description: t.description, methods: t.mcpTools?.map(m => ({ name: m.name, description: m.description, inputSchema: m.inputSchema, })), })); const systemPrompt = `You are an AI assistant with access to real-time tools. Available tools: ${JSON.stringify(toolDescriptions, null, 2)} If you need to use a tool, respond ONLY with JSON: { "toolId": "...", "toolName": "...", "args": {...} } If you can answer without a tool, just respond normally.`; // 3. Ask the LLM what to do const llmResponse = await myLLM.chat(userQuery, systemPrompt); // 4. Check if LLM wants to use a tool try { const toolCall = JSON.parse(llmResponse); if (toolCall.toolId && toolCall.toolName) { // 5. Execute the tool const result = await client.tools.execute({ toolId: toolCall.toolId, toolName: toolCall.toolName, args: toolCall.args || {}, }); // 6. Let LLM synthesize a bounded preview (avoid injecting giant JSON blobs) const resultPreview = JSON.stringify(result.result, null, 2).slice(0, 50_000); const resultKeys = result.result && typeof result.result === "object" ? Object.keys(result.result as Record) : []; return await myLLM.chat( `Tool "${toolCall.toolName}" returned keys: ${resultKeys.join(", ") || "(non-object result)"}\n\n` + `Preview (truncated):\n${resultPreview}\n\n` + `Please provide a helpful response to the user's original question: "${userQuery}" ``` ```APIDOC ); } } catch { // LLM responded with text, not JSON - return as-is return llmResponse; } } ``` ### Response #### Success Response - **string**: A synthesized response to the user's query, potentially including results from tool execution. ``` -------------------------------- ### Install MCP SDK for TypeScript (Direct Endpoint Testing) Source: https://github.com/ctxprotocol/sdk/blob/main/docs/mcp-contributor-deep-validation-system-prompt.md Use this command to install the SDK for direct endpoint testing with TypeScript. ```bash # For direct endpoint testing only npm install @modelcontextprotocol/sdk ``` -------------------------------- ### GET /portfolio/settlements Response Example Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Example of a success response for the GET /portfolio/settlements endpoint, showing the addition of the event_ticker field. ```json { "settlements": [ { "id": "s1t2u3v4", "event_ticker": "TSLA-20260115-100", "..." } ] } ``` -------------------------------- ### Copy Environment File Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/coinglass-contributor/README.md Copy the example environment file to .env and set your API key. This is the first step in setting up the server. ```bash cp env.example .env ``` -------------------------------- ### Build and Run Production Server Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/README.md Build the application for production and then start the server. ```bash npm run build npm start ``` -------------------------------- ### Get Event Forecast Percentile History Response Example Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Example of a success response for the Get Event Forecast Percentile History endpoint, showing historical forecast data. ```json { "forecast_history": [ { "timestamp": "2023-10-27T10:00:00Z", "forecast_raw": 0.75, "forecast_formatted": 75.0 } ] } ``` -------------------------------- ### GET /portfolio/orders/{order_id} API Example Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Retrieve the status and details of a specific order by its ID. This is a success response example. ```json { "order": { "id": "123", "status": "filled" } } ``` -------------------------------- ### GET /portfolio/orders API Example Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Retrieve a list of all orders associated with the user's portfolio. This is a success response example. ```json { "orders": [] } ``` -------------------------------- ### Install Dependencies and Run Server Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/hyperliquid-contributor/README.md Navigate to the project directory, install Node.js dependencies using pnpm, and then run the development server. The server will be accessible at http://localhost:4002. ```bash cd examples/server/hyperliquid-contributor pnpm install pnpm run dev ``` -------------------------------- ### GET /trade-api/v2/markets API Request Example Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Retrieves a list of available markets on the Kalshi platform, allowing users to filter by status and limit results. This is a request example. ```http GET https://demo-api.kalshi.co/trade-api/v2/markets?limit=1&status=open ``` -------------------------------- ### Get DEX Swap Quote Request Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/hummingbot-contributor/README.md Example JSON payload for the `get_dex_swap_quote` tool. Use this to get swap quotes from DEX aggregators like Jupiter or 0x. ```json { "tool": "get_dex_swap_quote", "arguments": { "connector": "jupiter", "network": "solana-mainnet-beta", "trading_pair": "SOL-USDC", "side": "BUY", "amount": 100 } } ``` -------------------------------- ### Client Initialization Source: https://github.com/ctxprotocol/sdk/blob/main/README.md Demonstrates how to initialize the ContextClient with different configurations for production and local development. ```APIDOC ## Client Options | Option | Type | Required | Default | | ------------------ | -------- | -------- | ------------------------------ | | `apiKey` | `string` | Yes | โ€” | | `baseUrl` | `string` | No | `https://www.ctxprotocol.com` | | `requestTimeoutMs` | `number` | No | `300000` | | `streamTimeoutMs` | `number` | No | `600000` | ```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", requestTimeoutMs: 420_000, streamTimeoutMs: 840_000, }); ``` ``` -------------------------------- ### GET /milestones Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Retrieves a list of milestones from the Kalshi platform, with an option to filter by a start date. ```APIDOC ## GET /milestones ### Description Retrieves a list of milestones from the Kalshi platform. ### Method GET ### Endpoint /milestones ### Parameters #### Query Parameters - **start_date** (string) - Optional - Minimum start date to filter milestones. Format: RFC3339 timestamp ### Response ``` -------------------------------- ### Export API Key Source: https://github.com/ctxprotocol/sdk/blob/main/examples/client/README.md Export your API key as an environment variable before running any example. Ensure you have completed the setup steps on ctxprotocol.com. ```bash export CONTEXT_API_KEY="sk_live_your_api_key" ``` -------------------------------- ### Subscribe to Markets Example - Python Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Demonstrates how to use the subscribe_to_markets function to get orderbook updates for specific markets or subscribe to the trade feed. ```python # Example usage: # Subscribe to orderbook updates await subscribe_to_markets(["orderbook_delta"], ["KXFUT24-LSV", "KXHARRIS24-LSV"]) # Subscribe to trade feed await subscribe_to_markets(["trade"], ["KXFUT24-LSV"]) ``` -------------------------------- ### Build and Run Server Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/polymarket-contributor/README.md Instructions for building and running the server using pnpm. ```bash pnpm build pnpm start ``` -------------------------------- ### Initialize ContextClient and Use Query/Execute Modes Source: https://github.com/ctxprotocol/sdk/blob/main/README.md Demonstrates initializing the ContextClient and performing basic operations in both Query and Execute modes. This serves as a quick start for integrating the SDK. ```typescript import { ContextClient } from "@ctxprotocol/sdk"; const client = new ContextClient({ apiKey: "sk_live_...", }); // Pay-per-response: Ask a question, get a managed answer package const answer = await client.query.run({ query: "What are the top whale movements on Base?", responseShape: "answer_with_evidence", }); console.log(answer.response); // Execute surface: require explicit execute pricing const tools = await client.discovery.search({ query: "gas prices", mode: "execute", surface: "execute", requireExecutePricing: true, }); const session = await client.tools.startSession({ maxSpendUsd: "1.00" }); const result = await client.tools.execute({ toolId: tools[0].id, toolName: tools[0].mcpTools[0].name, args: { chainId: 1 }, sessionId: session.session.sessionId ?? undefined, }); console.log(result.result); ``` -------------------------------- ### JSON: Get Query Results Example Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/dune-contributor/README.md Shows how to retrieve cached results for a specific Dune query ID using the `get_query_results` tool, with an optional limit. ```json { "tool": "get_query_results", "arguments": { "queryId": 3358886, "limit": 100 } } ``` -------------------------------- ### Manual Build Steps Source: https://github.com/ctxprotocol/sdk/blob/main/docs/mcp-builder-template.md Outlines the manual steps required to build an MCP server without AI assistance, covering API context, discovery questions, tool design, and implementation. ```text 1. Fill in [Section 1: API Context](#section-1-api-context) manually 2. Answer the [Discovery Questions](#section-2-discovery-questions) 3. Use the [Tool Design Framework](#section-3-tool-design-framework) 4. Follow the [Implementation Checklist](#section-5-implementation-checklist) ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/README.md Copy the example environment file and configure the port and Kalshi API base URL. For authenticated endpoints, provide API key and private key path. ```bash # Port (default: 4007) PORT=4007 # Kalshi API (public endpoints don't require auth) KALSHI_API_BASE_URL=https://api.elections.kalshi.com # For authenticated endpoints (portfolio management), you'll need: # - KALSHI_API_KEY_ID # - KALSHI_PRIVATE_KEY_PATH ``` -------------------------------- ### Fetch Kalshi Account Balance Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt This example demonstrates how to make an authenticated GET request to the Kalshi API to retrieve your account balance. It utilizes the `sign_request` function and requires your API Key ID, a valid signature, and the current timestamp. ```python import requests import datetime # Set up the request timestamp = str(int(datetime.datetime.now().timestamp() * 1000)) method = "GET" path = "/trade-api/v2/portfolio/balance" # Create signature (using function from Step 2) signature = sign_request(private_key, timestamp, method, path) # Make the request headers = { 'KALSHI-ACCESS-KEY': 'your-api-key-id', 'KALSHI-ACCESS-SIGNATURE': signature, 'KALSHI-ACCESS-TIMESTAMP': timestamp } response = requests.get('https://demo-api.kalshi.co' + path, headers=headers) balance = response.json() print(f"Your balance: ${balance['balance'] / 100:.2f}") ``` -------------------------------- ### Execute WebSocket Example Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Entry point to run the asynchronous WebSocket client. This code snippet is used to initiate the WebSocket connection. ```python # Run the example if __name__ == "__main__": asyncio.run(orderbook_websocket()) ``` -------------------------------- ### Send Kalshi API Request - Javascript Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Sends a GET request to the Kalshi API with necessary authentication headers. This example demonstrates how to combine private key loading, text signing, and Axios for making authenticated API calls. Ensure you replace placeholders with your actual API key and file path. ```javascript const axios = require('axios'); const currentTimeMilliseconds = Date.now(); const timestampStr = currentTimeMilliseconds.toString(); const privateKeyPem = loadPrivateKeyFromFile('path/to/your/private-key.pem'); const method = "GET"; const baseUrl = 'https://demo-api.kalshi.co'; const path = '/trade-api/v2/portfolio/balance'; // Strip query parameters from path before signing const pathWithoutQuery = path.split('?')[0]; const msgString = timestampStr + method + pathWithoutQuery; const sig = signPssText(privateKeyPem, msgString); const headers = { 'KALSHI-ACCESS-KEY': 'your-api-key-id', 'KALSHI-ACCESS-SIGNATURE': sig, 'KALSHI-ACCESS-TIMESTAMP': timestampStr }; axios.get(baseUrl + path, { headers }) .then(response => { console.log(response.data); }) .catch(error => { console.error('Error:', error); }); ``` -------------------------------- ### GET /markets and GET /markets/{ticker} - Settlement Timestamp Added Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt The `settlement_ts` field has been added to the responses of `GET /markets` and `GET /markets/{ticker}`. ```APIDOC ## GET /markets and GET /markets/{ticker} ### Description Added `settlement_ts` field to `GET /markets` and `GET /markets/{ticker}` responses. ### Method GET ### Endpoint /markets /markets/{ticker} ### Parameters None ### Request Example None ### Response #### Success Response (200) - **settlement_ts** (integer) - The Unix timestamp for when the market settles. - **...** (other fields) #### Response Example { "market_data": { "id": "a1b2c3d4", "ticker": "GOOG", "title": "Google Stock", "settlement_ts": 1672531200, "status": "active" } } ``` -------------------------------- ### Install Dependencies Source: https://github.com/ctxprotocol/sdk/blob/main/examples/client/README.md Install project dependencies using pnpm. Ensure you have pnpm installed globally. ```bash pnpm install ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/odds-api-contributor/README.md Copy the example environment file and add your API key. This is required for the server to authenticate with The Odds API. ```bash cp env.example .env # Edit .env and add your API key ``` -------------------------------- ### GET /markets and GET /markets/{ticker} - Deprecated Fields Removal Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt This update removes the deprecated fields `category` and `risk_limit_cents` from the responses of `GET /markets` and `GET /markets/{ticker}`. ```APIDOC ## GET /markets and GET /markets/{ticker} ### Description Deprecated fields `category` and `risk_limit_cents` have been removed from Market responses. ### Method GET ### Endpoint /markets /markets/{ticker} ### Parameters None ### Request Example None ### Response #### Success Response (200) - **market_data** (object) - Details about the market. - **...** (other fields) #### Response Example { "market_data": { "id": "a1b2c3d4", "ticker": "GOOG", "title": "Google Stock", "contracts": [ { "strike_price": 100, "last_price": 0.50, "volume": 1000, "open_interest": 500 } ], "status": "active", "last_update_ts": 1672531200 } } ### Release Date January 8, 2026 ``` -------------------------------- ### GET /live_data/{type}/milestone/{milestone_id} and GET /live_data/batch - Milestone ID Added Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt The `milestone_id` field has been added to the responses of `GET /live_data/{type}/milestone/{milestone_id}` and `GET /live_data/batch`. ```APIDOC ## GET /live_data/{type}/milestone/{milestone_id} and GET /live_data/batch ### Description Live Data responses now include the `milestone_id`. ### Method GET ### Endpoint /live_data/{type}/milestone/{milestone_id} /live_data/batch ### Parameters #### Path Parameters - **type** (string) - Required - The type of live data requested. - **milestone_id** (string) - Required - The ID of the milestone. ### Request Example None ### Response #### Success Response (200) - **milestone_id** (string) - The ID of the milestone. - **...** (other live data fields) #### Response Example { "milestone_id": "ms_abc123", "data": [ { "field": "value" } ] } ### Release Date December 4, 2025 ``` -------------------------------- ### Standard MCP Server Setup Source: https://github.com/ctxprotocol/sdk/blob/main/README.md Set up a standard MCP server using `@modelcontextprotocol/sdk`. Define tools with input and output schemas, and configure request handlers for listing tools and calling tools. ```typescript import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; // Define tools with outputSchema (standard MCP feature, required by Context) const TOOLS = [{ name: "get_gas_price", description: "Get current gas prices", inputSchema: { type: "object", properties: { chainId: { type: "number", description: "EVM chain ID" }, }, }, // ๐Ÿ‘‡ Standard MCP feature (see: modelcontextprotocol.io/specification) outputSchema: { type: "object", properties: { gasPrice: { type: "number" }, unit: { type: "string" }, }, required: ["gasPrice", "unit"], }, }]; // Standard MCP server setup const server = new Server( { name: "my-gas-tool", version: "1.0.0" }, { capabilities: { tools: {} } } ); server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS, // outputSchema is included automatically })); server.setRequestHandler(CallToolRequestSchema, async (request) => { const data = await fetchGasData(request.params.arguments.chainId); // ๐Ÿ‘‡ Standard MCP feature (see: modelcontextprotocol.io/specification) return { content: [{ type: "text", text: JSON.stringify(data) }], // Backward compat structuredContent: data, // Machine-readable, matches outputSchema }; }); ``` -------------------------------- ### Bash: Configure API Key and Install Dependencies Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/dune-contributor/README.md Sets up the Dune API key by creating a `.env` file and then installs project dependencies using npm. ```bash # 1. Configure API key echo 'DUNE_API_KEY="your_key_here"' > .env # 2. Install & run npm install npm run dev ``` -------------------------------- ### Install Dependencies Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/odds-api-contributor/README.md Install the necessary Node.js dependencies for the odds-api-contributor server. ```bash cd examples/server/odds-api-contributor npm install ``` -------------------------------- ### Run Development Server Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/README.md Start the Kalshi MCP server in development mode using npm. ```bash npm run dev ``` -------------------------------- ### Get Settlements Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Endpoint for getting the member's settlements historical track. ```APIDOC ## Get Settlements ### Description Endpoint for getting the member's settlements historical track. ### Method GET ### Endpoint /websites/kalshi/settlements ### Response #### Success Response (200) - **settlements** (array) - An array of settlement objects. - **settlement_id** (string) - The ID of the settlement. - **market_id** (string) - The ID of the market. - **event_id** (string) - The ID of the event. - **resolved_at** (string) - The timestamp when the settlement was resolved. - **status** (string) - The status of the settlement (e.g., "won", "lost"). ``` -------------------------------- ### Initialize Kalshi Client (Python) Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Configure the Python client with API credentials and perform a basic balance check. ```APIDOC ## Initialize Kalshi Client Source: https://docs.kalshi.com/python-sdk Configure the client with API credentials and perform a basic balance check. ```python from kalshi_python_sync import Configuration, KalshiClient # Configure the client config = Configuration( host="https://api.elections.kalshi.com/trade-api/v2" ) # For authenticated requests # Read private key from file with open("path/to/private_key.pem", "r") as f: private_key = f.read() config.api_key_id = "your-api-key-id" config.private_key_pem = private_key # Initialize the client client = KalshiClient(config) # Make API calls balance = client.get_balance() print(f"Balance: ${balance.balance / 100:.2f}") ``` ``` -------------------------------- ### Initialize Kalshi Python Client Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Configure the Python client with API credentials and perform a basic balance check. Requires API key ID and a private key loaded from a file. ```python from kalshi_python_sync import Configuration, KalshiClient # Configure the client config = Configuration( host="https://api.elections.kalshi.com/trade-api/v2" ) # For authenticated requests # Read private key from file with open("path/to/private_key.pem", "r") as f: private_key = f.read() config.api_key_id = "your-api-key-id" config.private_key_pem = private_key # Initialize the client client = KalshiClient(config) # Make API calls balance = client.get_balance() print(f"Balance: ${balance.balance / 100:.2f}") ``` -------------------------------- ### Kalshi and Polymarket Integration Example Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/README.md Demonstrates cross-platform composability by comparing market data from Kalshi and Polymarket to identify arbitrage opportunities. ```plaintext 1. Kalshi: browse_category({ category: "Politics" }) โ†’ "Trump wins" at 52ยข 2. Polymarket: search_markets({ query: "Trump" }) โ†’ same event at 48ยข 3. Arbitrage: 4% spread = potential profit ``` -------------------------------- ### Server Deployment and Setup Script Execution Source: https://github.com/ctxprotocol/sdk/blob/main/docs/mcp-builder-template.md Sequence of commands to deploy files, SSH into the server, configure environment variables, and run setup scripts for new MCP servers. ```bash # 1. Deploy files to server ./examples/server/deploy.sh # 2. SSH into the server ssh ubuntu@62.72.22.174 # 3. Create .env file for new server cd ~/mcp-servers/YOUR-NEW-SERVER-contributor cp env.example .env nano .env # Add your API keys # 4. Run setup script to install and start all servers cd ~/mcp-servers ./setup-servers.sh # 5. Update Caddy configuration for HTTPS sudo ./setup-caddy-https.sh # 6. Verify health check curl https://mcp.ctxprotocol.com/your-new-server/health ``` -------------------------------- ### Get Communications ID API Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Endpoint for getting the communications ID of the logged-in user. ```APIDOC ## GET /get_communications_id ### Description Endpoint for getting the communications ID of the logged-in user. ### Method GET ### Endpoint /get_communications_id ### Parameters This endpoint does not need any parameters. ### Response #### Success Response (200) - **GetCommunicationsIDResponse** - The communications ID of the logged-in user. #### Error Responses - **401** - Unauthorized - authentication required - **500** - Internal server error ``` -------------------------------- ### NPM Install Dependencies Source: https://github.com/ctxprotocol/sdk/blob/main/docs/mcp-builder-template.md Installs necessary packages for a TypeScript MCP server project. ```bash npm init -y npm install @modelcontextprotocol/sdk typescript npm install -D @types/node ts-node ``` -------------------------------- ### Retrieve Markets via Kalshi Python SDK Source: https://github.com/ctxprotocol/sdk/blob/main/examples/server/kalshi-contributor/validation/context7-kalshi-contributor-upstream-snapshot.txt Demonstrates how to initialize the Kalshi client using API credentials and call the get_markets method. The example includes optional parameters for filtering results and handling pagination via cursors. ```APIDOC ## Retrieve Markets via Kalshi Python SDK Source: https://docs.kalshi.com/python-sdk/api/MarketsApi Demonstrates how to initialize the Kalshi client using API credentials and call the get_markets method. The example includes optional parameters for filtering results and handling pagination via cursors. ```python import kalshi_python from kalshi_python.models.get_markets_response import GetMarketsResponse from kalshi_python.rest import ApiException from pprint import pprint # Configure the API client configuration = kalshi_python.Configuration( host = "https://api.elections.kalshi.com/trade-api/v2" ) # Load authentication credentials with open('path/to/private_key.pem', 'r') as f: private_key = f.read() configuration.api_key_id = "your-api-key-id" configuration.private_key_pem = private_key # Initialize the Kalshi client client = kalshi_python.KalshiClient(configuration) # Define optional filters params = { "limit": 100, "cursor": 'cursor_example', "event_ticker": 'event_ticker_example', "status": 'open' } try: # Execute the request api_response = client.get_markets(**params) print("The response of MarketsApi->get_markets:") pprint(api_response) except Exception as e: print("Exception when calling MarketsApi->get_markets: %s" % e) ``` ```