@ctxprotocol/sdk 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -10
- package/dist/client/index.cjs +3 -42
- package/dist/client/index.cjs.map +1 -1
- package/dist/client/index.d.cts +4 -5
- package/dist/client/index.d.ts +4 -5
- package/dist/client/index.js +3 -42
- package/dist/client/index.js.map +1 -1
- package/dist/contrib/search/index.d.cts +2 -2
- package/dist/contrib/search/index.d.ts +2 -2
- package/dist/index.cjs +3 -42
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -42
- package/dist/index.js.map +1 -1
- package/dist/{types-DPxI353c.d.cts → types-jbYPIQxq.d.cts} +158 -111
- package/dist/{types-DPxI353c.d.ts → types-jbYPIQxq.d.ts} +158 -111
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# @ctxprotocol/sdk
|
|
2
2
|
|
|
3
|
-
**
|
|
3
|
+
**Grounded context for your AI agents — on demand.**
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Give your agent the live facts it's missing. Context is a pay-per-response data marketplace: your agent discovers tools at runtime, buys the data its question needs, and drops it straight into its context window — no API keys, no servers, no per-source integration work.
|
|
6
6
|
|
|
7
7
|
Context Protocol is **npm for AI capabilities**. Just as you install packages to add functionality to your code, use the Context SDK to give your Agent instant access to thousands of live data sources and actions—from DeFi and Gas Oracles to Weather and Search.
|
|
8
8
|
|
|
@@ -11,15 +11,15 @@ Context Protocol is **npm for AI capabilities**. Just as you install packages to
|
|
|
11
11
|
|
|
12
12
|
---
|
|
13
13
|
|
|
14
|
-
###
|
|
14
|
+
### Contributors
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
List MCP tools on the permissionless Context marketplace and keep **90% of usage fees** in USDC.
|
|
17
17
|
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
18
|
+
- **Build:** Create an MCP server with this SDK
|
|
19
|
+
- **List:** Register at [ctxprotocol.com/contribute](https://ctxprotocol.com/contribute)
|
|
20
|
+
- **Earn:** Revenue share on every Query response and eligible Execute call
|
|
21
21
|
|
|
22
|
-
|
|
22
|
+
Grant batches open periodically — see [Developer Grants](https://docs.ctxprotocol.com/grants) for current batch status and contributor guidance.
|
|
23
23
|
|
|
24
24
|
---
|
|
25
25
|
|
|
@@ -96,7 +96,7 @@ const result = await client.tools.execute({
|
|
|
96
96
|
console.log(result.session); // methodPrice, spent, remaining, maxSpend, ...
|
|
97
97
|
```
|
|
98
98
|
|
|
99
|
-
**Query mode** gives you a managed librarian contract — the server runs the live pipeline (`discover -> select -> metadata scout ->
|
|
99
|
+
**Query mode** gives you a managed librarian contract — the server runs the live pipeline (`discover -> select -> metadata scout -> iterative execute -> synthesize -> settle`) with model-aware context budgeting and can return plain answers or structured evidence packages for one flat fee:
|
|
100
100
|
```typescript
|
|
101
101
|
const answer = await client.query.run({
|
|
102
102
|
query: "What are the top whale movements on Base?",
|
|
@@ -417,7 +417,7 @@ const closed = await client.tools.closeSession("sess_123");
|
|
|
417
417
|
|
|
418
418
|
#### `client.query.run(options)`
|
|
419
419
|
|
|
420
|
-
Run an agentic query. The server applies the live librarian pipeline (`discover -> select -> metadata scout ->
|
|
420
|
+
Run an agentic query. The server applies the live librarian pipeline (`discover -> select -> metadata scout -> iterative execute -> synthesize -> settle`) with up to 100 MCP calls per response turn, then returns the selected Query response contract (`answer`, `answer_with_evidence`, or `evidence_only`).
|
|
421
421
|
|
|
422
422
|
The query runtime now exposes a single managed executor surface.
|
|
423
423
|
The server decides internal budgets, ambiguity handling, and exploration policy
|
package/dist/client/index.cjs
CHANGED
|
@@ -53,9 +53,9 @@ var Developer = class {
|
|
|
53
53
|
if (!toolId) {
|
|
54
54
|
throw new ContextError("toolId is required");
|
|
55
55
|
}
|
|
56
|
-
if (updates.name === void 0 && updates.description === void 0 && updates.category === void 0) {
|
|
56
|
+
if (updates.name === void 0 && updates.description === void 0 && updates.suggestedPrompts === void 0 && updates.category === void 0) {
|
|
57
57
|
throw new ContextError(
|
|
58
|
-
"At least one field required: name, description, or category"
|
|
58
|
+
"At least one field required: name, description, suggestedPrompts, or category"
|
|
59
59
|
);
|
|
60
60
|
}
|
|
61
61
|
if (updates.category !== void 0 && updates.category !== null && !ALLOWED_TOOL_CATEGORIES.includes(updates.category)) {
|
|
@@ -304,9 +304,6 @@ var Query = class {
|
|
|
304
304
|
}
|
|
305
305
|
normalizeResult(result) {
|
|
306
306
|
const candidate = result;
|
|
307
|
-
if (candidate.outcomeType === "clarification_required" && "clarification" in candidate && candidate.clarification) {
|
|
308
|
-
return candidate;
|
|
309
|
-
}
|
|
310
307
|
if (candidate.outcomeType === "capability_miss" && "capabilityMiss" in candidate && candidate.capabilityMiss) {
|
|
311
308
|
return candidate;
|
|
312
309
|
}
|
|
@@ -315,34 +312,6 @@ var Query = class {
|
|
|
315
312
|
outcomeType: "answer"
|
|
316
313
|
};
|
|
317
314
|
}
|
|
318
|
-
buildPolicyErrorEvent(params) {
|
|
319
|
-
if (params.clarificationPolicy !== "error") {
|
|
320
|
-
return;
|
|
321
|
-
}
|
|
322
|
-
if (params.result.outcomeType === "clarification_required") {
|
|
323
|
-
return {
|
|
324
|
-
type: "error",
|
|
325
|
-
error: params.result.response,
|
|
326
|
-
code: "clarification_required",
|
|
327
|
-
reasonCode: "clarification_required",
|
|
328
|
-
outcomeType: "clarification_required",
|
|
329
|
-
clarification: params.result.clarification,
|
|
330
|
-
querySession: params.result.querySession
|
|
331
|
-
};
|
|
332
|
-
}
|
|
333
|
-
if (params.result.outcomeType === "capability_miss") {
|
|
334
|
-
return {
|
|
335
|
-
type: "error",
|
|
336
|
-
error: params.result.response,
|
|
337
|
-
code: "capability_miss",
|
|
338
|
-
reasonCode: "capability_miss",
|
|
339
|
-
outcomeType: "capability_miss",
|
|
340
|
-
capabilityMiss: params.result.capabilityMiss,
|
|
341
|
-
querySession: params.result.querySession
|
|
342
|
-
};
|
|
343
|
-
}
|
|
344
|
-
return void 0;
|
|
345
|
-
}
|
|
346
315
|
buildSyntheticTraceFromRunResult(params) {
|
|
347
316
|
const timeline = params.toolsUsed.map((tool, index) => ({
|
|
348
317
|
stepType: "tool-call",
|
|
@@ -556,7 +525,6 @@ var Query = class {
|
|
|
556
525
|
tools: opts.tools,
|
|
557
526
|
resumeFrom: opts.resumeFrom,
|
|
558
527
|
forkFrom: opts.forkFrom,
|
|
559
|
-
clarificationPolicy: opts.clarificationPolicy,
|
|
560
528
|
answerModelId: opts.answerModelId,
|
|
561
529
|
responseShape: opts.responseShape,
|
|
562
530
|
favoritesOnly: opts.favoritesOnly,
|
|
@@ -614,13 +582,6 @@ var Query = class {
|
|
|
614
582
|
normalizedResult.developerTrace = mergedTrace;
|
|
615
583
|
}
|
|
616
584
|
event.result = normalizedResult;
|
|
617
|
-
const policyErrorEvent = this.buildPolicyErrorEvent({
|
|
618
|
-
result: normalizedResult,
|
|
619
|
-
clarificationPolicy: opts.clarificationPolicy
|
|
620
|
-
});
|
|
621
|
-
if (policyErrorEvent) {
|
|
622
|
-
return policyErrorEvent;
|
|
623
|
-
}
|
|
624
585
|
}
|
|
625
586
|
return event;
|
|
626
587
|
};
|
|
@@ -691,7 +652,7 @@ var ContextClient = class {
|
|
|
691
652
|
*
|
|
692
653
|
* Unlike `tools.execute()` which calls a single tool once, `query` sends
|
|
693
654
|
* a natural-language question and lets the server handle discovery,
|
|
694
|
-
* metadata scout,
|
|
655
|
+
* metadata scout, iterative execution, and AI synthesis —
|
|
695
656
|
* one flat fee.
|
|
696
657
|
*/
|
|
697
658
|
query;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/client/types.ts","../../src/client/resources/developer.ts","../../src/client/resources/discovery.ts","../../src/client/resources/tools.ts","../../src/client/resources/query.ts","../../src/client/client.ts"],"names":[],"mappings":";;;AAoQO,IAAM,uBAAA,GAA0B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nC,QAAA,MAAM,IAAI,YAAA;AAAA,UACR,CAAA,kCAAA,EAAqC,IAAA,CAAK,eAAA,GAAkB,GAAI,CAAA,CAAA,CAAA;AAAA,UAChE,MAAA;AAAA,UACA;AAAA,SACF;AAAA,MACF;AACA,MAAA,MAAM,IAAI,YAAA,CAAa,SAAA,CAAU,OAAO,CAAA;AAAA,IAC1C;AAEA,IAAA,YAAA,CAAa,OAAO,CAAA;AAEpB,IAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,MAAA,IAAI,eAAe,CAAA,KAAA,EAAQ,QAAA,CAAS,MAAM,CAAA,EAAA,EAAK,SAAS,UAAU,CAAA,CAAA;AAClE,MAAA,IAAI,SAAA;AACJ,MAAA,IAAI,OAAA;AAEJ,MAAA,IAAI;AACF,QAAA,MAAM,SAAA,GAAY,MAAM,QAAA,CAAS,IAAA,EAAK;AACtC,QAAA,IAAI,UAAU,KAAA,EAAO;AACnB,UAAA,YAAA,GAAe,SAAA,CAAU,KAAA;AACzB,UAAA,SAAA,GAAY,SAAA,CAAU,IAAA;AACtB,UAAA,OAAA,GAAU,SAAA,CAAU,OAAA;AAAA,QACtB;AAAA,MACF,CAAA,CAAA,MAAQ;AAAA,MAER;AAEA,MAAA,MAAM,IAAI,YAAA,CAAa,YAAA,EAAc,SAAA,EAAW,QAAA,CAAS,QAAQ,OAAO,CAAA;AAAA,IAC1E;AAEA,IAAA,OAAO,QAAA;AAAA,EACT;AACF","file":"index.cjs","sourcesContent":["import type { ContributorSearchTraceRecord } from \"../contrib/search/types.js\";\n\n/**\n * Configuration options for initializing the ContextClient\n */\nexport interface ContextClientOptions {\n /**\n * Your Context Protocol API key\n * @example \"sk_live_abc123...\"\n */\n apiKey: string;\n\n /**\n * Base URL for the Context Protocol API\n * @default \"https://www.ctxprotocol.com\"\n */\n baseUrl?: string;\n\n /**\n * Request timeout for non-streaming API calls in milliseconds.\n * @default 300000\n */\n requestTimeoutMs?: number;\n\n /**\n * Request timeout for establishing streaming API calls in milliseconds.\n * @default 600000\n */\n streamTimeoutMs?: number;\n}\n\n/**\n * An individual MCP tool exposed by a tool listing\n */\nexport interface McpToolRateLimitHints {\n /** Suggested request budget for this method */\n maxRequestsPerMinute?: number;\n\n /** Suggested parallel call ceiling for this method */\n maxConcurrency?: number;\n\n /** Suggested minimum delay between sequential calls */\n cooldownMs?: number;\n\n /** Whether this method already supports bulk/batch retrieval */\n supportsBulk?: boolean;\n\n /** Preferred batch-oriented methods to call instead of fan-out loops */\n recommendedBatchTools?: string[];\n\n /** Optional human-readable notes for execution behavior */\n notes?: string;\n}\n\nexport type DiscoveryMode = \"query\" | \"execute\";\nexport type McpToolSurface = \"answer\" | \"execute\" | \"both\";\nexport type McpToolLatencyClass = \"instant\" | \"fast\" | \"slow\" | \"streaming\";\n\nexport interface McpToolPricingMeta {\n executeUsd?: string;\n queryUsd?: string;\n [key: string]: unknown;\n}\n\nexport interface McpToolMeta {\n /** Declared method surface */\n surface?: McpToolSurface;\n\n /** Whether this method can be selected in query mode */\n queryEligible?: boolean;\n\n /** Declared latency class for metadata-scout/runtime gating */\n latencyClass?: McpToolLatencyClass;\n\n /** Method-level pricing metadata */\n pricing?: McpToolPricingMeta;\n\n /** Derived discovery flag for execute eligibility */\n executeEligible?: boolean;\n\n /** Derived discovery field for explicit execute pricing visibility */\n executePriceUsd?: string;\n\n /** Context injection requirements handled by the Context runtime */\n contextRequirements?: string[];\n\n /**\n * Optional metadata-scout/runtime pacing hints.\n * Tool contributors can publish these to reduce rate-limit failures.\n */\n rateLimit?: McpToolRateLimitHints;\n rateLimitHints?: McpToolRateLimitHints;\n\n /** Flat aliases accepted for convenience */\n maxRequestsPerMinute?: number;\n maxConcurrency?: number;\n cooldownMs?: number;\n supportsBulk?: boolean;\n recommendedBatchTools?: string[];\n notes?: string;\n\n [key: string]: unknown;\n}\n\nexport interface StructuredMethodGuidanceHints {\n /** Suggested call-order sequence extracted from method descriptions */\n callOrderHints?: string[];\n\n /** Parameter usage caveats extracted from method descriptions */\n parameterCaveats?: string[];\n\n /** Edge-case behavior notes extracted from method descriptions */\n edgeCaseNotes?: string[];\n}\n\nexport interface McpTool {\n /** Name of the MCP tool method */\n name: string;\n\n /** Description of what this method does */\n description: string;\n\n /**\n * JSON Schema for the input arguments this tool accepts.\n * Used by LLMs to generate correct arguments.\n */\n inputSchema?: Record<string, unknown>;\n\n /**\n * JSON Schema for the output this tool returns.\n * Used by LLMs to understand the response structure.\n */\n outputSchema?: Record<string, unknown>;\n\n /** MCP metadata extensions (context injection, rate-limit hints) */\n _meta?: McpToolMeta;\n\n /** Explicit execute eligibility in discovery responses */\n executeEligible?: boolean;\n\n /** Explicit execute price visibility in discovery responses */\n executePriceUsd?: string | null;\n\n /** Whether this method has normalized structured guidance hints */\n hasStructuredGuidance?: boolean;\n\n /** Optional structured guidance hints derived from the method description */\n structuredGuidance?: StructuredMethodGuidanceHints;\n}\n\n/**\n * Represents a tool available on the Context Protocol marketplace\n */\nexport interface Tool {\n /** Unique identifier for the tool (UUID) */\n id: string;\n\n /** Human-readable name of the tool */\n name: string;\n\n /** Description of what the tool does */\n description: string;\n\n /** Price per execution in USDC */\n price: string;\n\n /** Tool category (e.g., \"defi\", \"nft\") */\n category?: string;\n\n /** Whether the tool is verified by Context Protocol */\n isVerified?: boolean;\n\n /** Tool type - currently always \"mcp\" */\n kind?: string;\n\n /**\n * Available MCP tool methods\n * Use items from this array as `toolName` when executing\n */\n mcpTools?: McpTool[];\n\n // Trust metrics (Level 2 - Reputation Ledger)\n /** Total number of queries processed */\n totalQueries?: number;\n\n /** Success rate percentage (0-100) */\n successRate?: string;\n\n /** Uptime percentage (0-100) */\n uptimePercent?: string;\n\n /** Total USDC staked by the developer */\n totalStaked?: string;\n\n /** Whether the tool has \"Proven\" status (100+ queries, >95% success, >98% uptime) */\n isProven?: boolean;\n}\n\n/**\n * Response from the tools search endpoint\n */\nexport interface SearchResponse {\n /** Array of matching tools */\n tools: Tool[];\n\n /** Discovery mode used by the server */\n mode?: DiscoveryMode;\n\n /** The search query that was used */\n query: string;\n\n /** Total number of results */\n count: number;\n}\n\n/**\n * Options for searching tools\n */\nexport interface SearchOptions {\n /** Search query (semantic search) */\n query?: string;\n\n /** Maximum number of results (1-50, default 10) */\n limit?: number;\n\n /** Discovery mode with billing semantics */\n mode?: DiscoveryMode;\n\n /** Optional explicit method surface filter */\n surface?: McpToolSurface;\n\n /** Require methods marked query eligible */\n queryEligible?: boolean;\n\n /** Require explicit method execute pricing */\n requireExecutePricing?: boolean;\n\n /** Exclude methods by latency class */\n excludeLatencyClasses?: McpToolLatencyClass[];\n\n /** Convenience switch to exclude slow methods in query mode */\n excludeSlow?: boolean;\n\n /**\n * Restrict discovery to the caller's favorite tools.\n * - `true`: force favorites-only discovery for this request\n * - `false`: force unrestricted discovery for this request\n * - omitted: use the account-level default from Context settings\n */\n favoritesOnly?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Developer / tool management types\n// ---------------------------------------------------------------------------\n\n/**\n * Options for updating a tool listing via `client.developer.updateTool()`.\n * At least one field must be provided.\n */\nexport const ALLOWED_TOOL_CATEGORIES = [\n \"Crypto & DeFi\",\n \"Financial Markets\",\n \"Business & Sales\",\n \"Marketing & SEO\",\n \"Legal & Regulatory\",\n \"Real World\",\n \"Developer Tools\",\n \"Research & Academia\",\n \"Utility\",\n \"Other\",\n] as const;\n\nexport type ToolCategory = (typeof ALLOWED_TOOL_CATEGORIES)[number];\n\nexport interface UpdateToolOptions {\n /** New display name for the tool */\n name?: string;\n\n /** New marketplace description */\n description?: string;\n\n /** New category -- must be one of the predefined marketplace categories */\n category?: ToolCategory | null;\n}\n\n/**\n * Response from updating a tool listing.\n */\nexport interface UpdateToolResult {\n id: string;\n name: string;\n description: string;\n category: string | null;\n updatedAt: string;\n}\n\n/**\n * Options for executing a tool\n */\nexport interface ExecuteOptions {\n /** The UUID of the tool to execute (from search results) */\n toolId: string;\n\n /** The specific MCP tool name to call (from tool's mcpTools array) */\n toolName: string;\n\n /** Arguments to pass to the tool */\n args?: Record<string, unknown>;\n\n /**\n * Optional idempotency key (UUID recommended).\n * Reuse the same key when retrying the same logical request.\n */\n idempotencyKey?: string;\n\n /** Explicit execute mode label for request clarity */\n mode?: \"execute\";\n\n /** Optional execute session identifier */\n sessionId?: string;\n\n /** Optional per-session spend budget envelope (USD) */\n maxSpendUsd?: string;\n\n /** Request session closure after this execute call settles */\n closeSession?: boolean;\n}\n\nexport type ExecuteSessionStatus = \"open\" | \"closed\" | \"expired\";\n\nexport interface ExecuteSessionSpend {\n mode: \"execute\";\n sessionId: string | null;\n methodPrice: string;\n spent: string;\n remaining: string | null;\n maxSpend: string | null;\n\n /** Optional lifecycle fields when the API returns session state */\n status?: ExecuteSessionStatus;\n expiresAt?: string;\n closeRequested?: boolean;\n pendingAccruedCount?: number;\n pendingAccruedUsd?: string;\n}\n\n/**\n * Successful execution response from the API\n */\nexport interface ExecuteApiSuccessResponse {\n success: true;\n mode: \"execute\";\n\n /** The result data from the tool execution */\n result: unknown;\n\n /** Information about the executed tool */\n tool: {\n id: string;\n name: string;\n };\n\n /** Method-level execute pricing used for this call */\n method: {\n name: string;\n executePriceUsd: string;\n };\n\n /** Spend envelope visibility for execute sessions */\n session: ExecuteSessionSpend;\n\n /** Execution duration in milliseconds */\n durationMs: number;\n}\n\n/**\n * Error response from the API\n */\nexport interface ExecuteApiErrorResponse {\n /** Human-readable error message */\n error: string;\n\n /** Explicit mode label for clarity */\n mode?: \"execute\";\n\n /** Error code for programmatic handling */\n code?: ContextErrorCode;\n\n /** URL to help resolve the issue */\n helpUrl?: string;\n\n /** Optional spend envelope context when available */\n session?: ExecuteSessionSpend;\n}\n\n/**\n * Raw API response from the execute endpoint\n */\nexport type ExecuteApiResponse = ExecuteApiSuccessResponse | ExecuteApiErrorResponse;\n\nexport interface ExecuteSessionStartOptions {\n /** Maximum spend budget for the session (USD string) */\n maxSpendUsd: string;\n}\n\nexport interface ExecuteSessionApiSuccessResponse {\n success: true;\n mode: \"execute\";\n session: ExecuteSessionSpend;\n}\n\nexport type ExecuteSessionApiResponse =\n | ExecuteSessionApiSuccessResponse\n | ExecuteApiErrorResponse;\n\nexport interface ExecuteSessionResult {\n mode: \"execute\";\n session: ExecuteSessionSpend;\n}\n\n/**\n * The resolved result returned to the user after SDK processing\n */\nexport interface ExecutionResult<T = unknown> {\n mode: \"execute\";\n\n /** The data returned by the tool */\n result: T;\n\n /** Information about the executed tool */\n tool: {\n id: string;\n name: string;\n };\n\n /** Method-level execute pricing used for this call */\n method: {\n name: string;\n executePriceUsd: string;\n };\n\n /** Spend envelope visibility for execute calls */\n session: ExecuteSessionSpend;\n\n /** Execution duration in milliseconds */\n durationMs: number;\n}\n\n// ---------------------------------------------------------------------------\n// Query types (pay-per-response / agentic mode)\n// ---------------------------------------------------------------------------\n\n/** Supported orchestration depth modes for query execution. */\nexport type QueryDepth = \"fast\" | \"auto\" | \"deep\";\nexport type QueryDeepMode = \"deep\" | \"deep-light\" | \"deep-heavy\";\nexport type QueryClarificationPolicy = \"return\" | \"auto\" | \"error\";\nexport type QueryOutcomeType =\n | \"answer\"\n | \"clarification_required\"\n | \"capability_miss\";\nexport type QueryResponseShape =\n | \"answer\"\n | \"answer_with_evidence\"\n | \"evidence_only\";\nexport type QueryResponseEnvelopeViewType =\n | \"table\"\n | \"leaderboard\"\n | \"heatmap\"\n | \"timeseries\";\n\nexport interface QueryClarificationOption {\n id: string;\n toolId: string;\n toolName: string;\n methodName: string;\n label: string;\n description: string;\n fitScore: number;\n recommended: boolean;\n}\n\nexport interface QueryClarificationPayload {\n question: string;\n options: QueryClarificationOption[];\n allowFreeform: boolean;\n recommendedOptionId: string;\n originalQuery: string;\n}\n\nexport interface QueryCapabilityMissPayload {\n message: string;\n missingCapabilities: string[];\n suggestedRewrites: string[];\n originalQuery: string;\n}\n\nexport interface QueryAssumptionMetadata {\n mode: \"auto\";\n optionId: string;\n label: string;\n reason: string;\n}\n\nexport type QueryClarificationDecisionReasonCode =\n | \"rollout_disabled\"\n | \"no_grounded_candidates\"\n | \"single_grounded_interpretation\"\n | \"required_discriminator_ambiguity\"\n | \"contract_scope_ambiguity\"\n | \"cost_or_latency_ambiguity\"\n | \"semantic_scope_ambiguity\"\n | \"capability_miss\";\n\nexport type QueryAttemptForkReason =\n | \"manual_fork\"\n | \"clarification_branch\"\n | \"bounded_rediscovery\"\n | \"resume_replay\"\n | \"patch_retry\"\n | \"unknown\";\n\nexport interface QueryClarificationEvidenceSources {\n usesMethodSchemas: boolean;\n usesProbeArgs: boolean;\n usesMethodMetadata: boolean;\n usesToolSelectionContext: boolean;\n usesLlmSelection: boolean;\n}\n\nexport interface QueryClarificationCandidateSummary {\n optionId: string;\n fitScore: number;\n llmRelevanceScore: number | null;\n requiredParams: string[];\n unresolvedRequiredParams: string[];\n probeArgKeys: string[];\n inputFieldNames: string[];\n outputKeys: string[];\n latencyClass: string;\n executePriceUsd: string | null;\n queryEligible: boolean;\n}\n\nexport interface QueryClarificationDiagnostics {\n orchestrationMode: string;\n rolloutStage: string;\n shadowMode: boolean;\n policy: QueryClarificationPolicy;\n outcomeType: QueryOutcomeType;\n triggered: boolean;\n optionCount: number;\n candidateCount: number;\n viableCandidateCount: number;\n recommendedOptionId: string | null;\n recommendedOptionReason: string | null;\n autoResolved: boolean;\n autoSelectEnabled: boolean;\n assumptionMade: QueryAssumptionMetadata | null;\n missingCapability: string | null;\n decisionReasonCode: QueryClarificationDecisionReasonCode;\n decisionSignals: string[];\n evidenceSources: QueryClarificationEvidenceSources;\n comparedOptionIds: string[];\n decisionStrategy: \"deterministic\" | \"llm_primary\";\n judgeAttempted: boolean;\n judgeApplied: boolean;\n judgeOutcomeType: QueryOutcomeType | null;\n judgeConfidence: number | null;\n judgeReason: string | null;\n judgeError: string | null;\n validatorReason: string | null;\n fallbackReason: string | null;\n copyStrategy: \"deterministic\" | \"llm_rewritten\";\n rewriteAttempted: boolean;\n rewriteApplied: boolean;\n rewriteError: string | null;\n candidateSummaries: QueryClarificationCandidateSummary[];\n}\n\n/**\n * Options for the agentic query endpoint (pay-per-response).\n *\n * Unlike `execute()` which calls a single tool once, `query()` sends a\n * natural-language question and lets the server handle the live librarian\n * pipeline (`discover -> select -> metadata scout -> clarify if needed ->\n * iterative execute -> synthesize -> settle`).\n * One flat fee covers up to 100 MCP skill calls per tool.\n */\nexport interface QueryOptions {\n /** The natural-language question to answer */\n query: string;\n\n /**\n * How the SDK should handle clarification-required situations:\n * - `return`: surface a structured clarification result to the caller\n * - `auto`: enable clarification auto-select and continue with the server's deterministic recommended option\n * - `error`: turn structured clarification/capability outcomes into terminal errors\n *\n * Default behavior is surface-dependent: headless SDK and MCP callers default\n * to `auto`, while first-party chat defaults to `return`.\n */\n clarificationPolicy?: QueryClarificationPolicy;\n\n /**\n * Optional tool IDs to use. When omitted the server discovers tools\n * automatically (Auto Mode). When provided, only these tools are used\n * (Manual Mode).\n */\n tools?: string[];\n\n /**\n * Restrict auto-discovery to the caller's favorite tools.\n * Ignored when `tools` is provided because manual tool selection wins.\n * - `true`: force favorites-only discovery for this request\n * - `false`: force unrestricted discovery for this request\n * - omitted: use the account-level default from Context settings\n */\n favoritesOnly?: boolean;\n\n /**\n * Resume a prior durable query attempt from its latest checkpoint.\n * Cannot be combined with `tools` or `forkFrom`.\n */\n resumeFrom?: QueryAttemptReference;\n\n /**\n * Fork a new durable query attempt from a previous attempt.\n * Optional `reason` keeps the server's non-breaking lineage metadata honest.\n * Cannot be combined with `tools` or `resumeFrom`.\n */\n forkFrom?: QueryForkReference;\n\n /**\n * Optional answer model ID for final synthesis.\n * Supported IDs are published by the Context API. Ignored when\n * `responseShape` is `evidence_only` because synthesis is skipped.\n */\n answerModelId?: string;\n\n /**\n * Structured response mode for query answers.\n * - `answer`: backward-compatible natural-language answer\n * - `answer_with_evidence`: prose answer plus a structured evidence package\n * - `evidence_only`: structured evidence package with a machine-friendly summary\n */\n responseShape?: QueryResponseShape;\n\n /**\n * Include execution data inline in the query response.\n * Useful for headless agents that need raw structured outputs.\n * Handshake completion remains a chat-only flow today; raw execution data\n * is not a typed resume/callback contract for approvals.\n */\n includeData?: boolean;\n\n /**\n * Persist execution data to Vercel Blob and return a download URL.\n * Useful for large payload workflows where inline JSON is not ideal.\n */\n includeDataUrl?: boolean;\n\n /**\n * Include machine-readable developer trace output for this query response.\n * When enabled, the server may return summary counters plus diagnostics\n * for lane selection, metadata scout adequacy, clarification, and iterative\n * execution behavior.\n */\n includeDeveloperTrace?: boolean;\n\n /**\n * Optional idempotency key (UUID recommended).\n * Reuse the same key when retrying the same logical request.\n */\n idempotencyKey?: string;\n}\n\n/**\n * Tool reference attached to developer trace timeline steps.\n */\nexport interface QueryDeveloperTraceToolRef {\n id?: string;\n name?: string;\n method?: string;\n [key: string]: unknown;\n}\n\n/**\n * Loop metadata attached to developer trace timeline steps.\n */\nexport interface QueryDeveloperTraceLoopInfo {\n name?: string;\n iteration?: number;\n maxIterations?: number;\n [key: string]: unknown;\n}\n\n/**\n * Tool selection metadata attached to discovery and metadata-scout diagnostics.\n */\nexport interface QueryDeveloperTraceToolSelection {\n toolId: string;\n toolName: string;\n selectedMethodCount: number;\n selectedMethods: string[];\n omittedSelectedMethodCount: number;\n priceUsd?: string;\n}\n\n/**\n * Execution-contract details handed to the iterative runtime.\n */\nexport interface QueryPlanningTraceDiagnostic {\n plannerQuery: string;\n scoutEvidenceAttached: boolean;\n scoutEvidencePromptBlock: string | null;\n allowedModules: string[];\n}\n\n/**\n * Rediscovery/fallback diagnostic details.\n */\nexport interface QueryRediscoveryTraceDiagnostic {\n considered: boolean;\n executed: boolean;\n skipReason: string | null;\n missingCapability: string | null;\n rediscoveryQuery: string | null;\n capabilityLooksLikeSearchNeed: boolean;\n allowSearchFallbackOnElapsedCap: boolean;\n searchFallbackUsed: boolean;\n preRediscoveryBudgetReasonCode: string | null;\n candidateSearchResults: QueryDeveloperTraceToolSelection[];\n selectedAlternatives: QueryDeveloperTraceToolSelection[];\n mergedTools: QueryDeveloperTraceToolSelection[];\n usingPaidFallback: boolean;\n branchPlan: QueryPlanningTraceDiagnostic | null;\n}\n\nexport interface QueryCompletenessRepairEvent {\n attempt: number;\n outcome:\n | \"attempted\"\n | \"skipped_by_guardrail\"\n | \"skipped_no_retry_budget\"\n | \"skipped_needs_different_tools\"\n | \"skipped_no_retry_path\"\n | \"patch_failed\"\n | \"replan_failed\"\n | \"patched\"\n | \"replanned\";\n semanticRetryCount: number;\n maxSemanticRetries: number;\n strategy: \"patch\" | \"replan\" | null;\n summary: string | null;\n failReason: string | null;\n requestedReplan: boolean;\n hadSyntaxFix: boolean;\n editCount: number | null;\n skipReason: string | null;\n boundedAnswerReason:\n | \"retry_guardrail_same_endpoint_fanout\"\n | \"retry_guardrail_upstream_abort\"\n | null;\n blockingDiagnostics: Array<{\n code: string;\n severity: string;\n message: string;\n }>;\n}\n\n/**\n * Rich developer-trace diagnostics for managed query-runtime internals.\n */\nexport interface QueryDeveloperTraceDiagnostics {\n selection: {\n selectedPolicy: string;\n debugScoutDeepMode: string | null;\n plannerReasoningStage: string;\n scoutEnabled: boolean;\n oneShotBias: boolean;\n candidateMethodCount: number;\n scoutProbeStatus: string;\n scoutProbeAdequacy: string;\n scoutProbeConfidence: number;\n scoutMetadataConfidence: number;\n scoutProbeQuerySafeCandidateCount: number;\n scoutProbeRankedMethodCount: number;\n scoutProbeAmbiguityPoolCount: number;\n scoutProbeShortlistedMethodCount: number;\n scoutProbeMissingCapability: string | null;\n scoutPrePlanProbeCalls: number;\n scoutPrePlanProbeBudgetReasonCode: string | null;\n scoutChangedInitialPlan: boolean;\n scoutChangedPlannerReasoningStage: boolean;\n scoutInitialSelectedPolicy: string;\n scoutInitialPlannerReasoningStage: string;\n scoutInitialReasonCode: string;\n scoutFinalReasonCode: string;\n scoutEvidenceAttachedToPlanning: boolean;\n scoutLlmSelectionUsed: boolean;\n scoutLlmSelectionFallback: boolean;\n scoutLlmSelectionLatencyMs: number | null;\n selectedTools: QueryDeveloperTraceToolSelection[];\n };\n executionContract?: QueryPlanningTraceDiagnostic;\n cost?: {\n planningCostUsd: number;\n initialExecutionCostUsd: number;\n rediscoveryAdditionalCostUsd: number;\n synthesisCostUsd: number;\n totalModelCostUsd: number;\n toolCostUsd: number;\n totalChargedUsd: number;\n };\n verification: {\n evaluations: unknown[];\n repairEvents: QueryCompletenessRepairEvent[];\n triggerNeedsDifferentTools: boolean;\n triggerMissingCapability: string | null;\n };\n execution?: {\n reasoningEnabled: boolean;\n receivedReasoning: boolean;\n reasoningChars: number;\n scoutEvidenceInjected: boolean;\n stepBudget: number;\n completedStepCount: number;\n };\n clarification?: QueryClarificationDiagnostics;\n contributorSearches?: ContributorSearchTraceRecord[];\n [key: string]: unknown;\n}\n\n/**\n * A single developer-trace timeline step.\n */\nexport interface QueryDeveloperTraceStep {\n stepType?: string;\n event?: string;\n status?: string;\n message?: string;\n timestampMs?: number;\n tool?: QueryDeveloperTraceToolRef;\n attempt?: number;\n loop?: QueryDeveloperTraceLoopInfo;\n metadata?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n/**\n * Aggregate counters that summarize developer-trace behavior.\n */\nexport interface QueryDeveloperTraceSummary {\n toolCalls?: number;\n retryCount?: number;\n selfHealCount?: number;\n fallbackCount?: number;\n failureCount?: number;\n recoveryCount?: number;\n completionChecks?: number;\n loopCount?: number;\n [key: string]: unknown;\n}\n\n/**\n * Full tool call record (untruncated) for debugging.\n */\nexport interface QueryDeveloperTraceToolCall {\n toolId?: string;\n toolName: string;\n args?: unknown;\n result: unknown;\n}\n\n/**\n * MCP method schema exposed in the developer trace.\n */\nexport interface QueryDeveloperTraceToolSchema {\n serverName: string;\n toolName: string;\n description: string;\n inputSchema?: Record<string, unknown>;\n outputSchema?: Record<string, unknown>;\n}\n\n/**\n * Developer Mode trace payload returned per query response (opt-in).\n */\nexport interface QueryDeveloperTrace {\n summary?: QueryDeveloperTraceSummary;\n timeline?: QueryDeveloperTraceStep[];\n requestId?: string;\n query?: string;\n source?: string;\n diagnostics?: QueryDeveloperTraceDiagnostics;\n initialCode?: string;\n finalCode?: string;\n executionTrace?: unknown[];\n executionProgram?: unknown;\n attemptCount?: number;\n executionSuccess?: boolean;\n executionResult?: unknown;\n toolCallHistory?: QueryDeveloperTraceToolCall[];\n toolSchemas?: QueryDeveloperTraceToolSchema[];\n [key: string]: unknown;\n}\n\n/**\n * Information about a tool that was used during a query response\n */\nexport interface QueryToolUsage {\n /** Tool ID */\n id: string;\n\n /** Tool name */\n name: string;\n\n /** Number of MCP skill calls made for this tool */\n skillCalls: number;\n}\n\n/**\n * Cost breakdown for a query response.\n * All values are strings representing USD amounts.\n */\nexport interface QueryCost {\n /** AI model inference cost */\n modelCostUsd: string;\n\n /** Sum of all tool fees */\n toolCostUsd: string;\n\n /** Total cost (model + tools) */\n totalCostUsd: string;\n}\n\n/**\n * High-level orchestration outcome metrics returned by the query API.\n */\nexport interface QueryOrchestrationMetrics {\n parityStage: string;\n orchestrationMode: string;\n /** Whether the first plan path succeeded without fallback. */\n firstPassSuccess: boolean;\n /** Whether execution signaled a missing capability on first pass. */\n capabilityMissSignaled: boolean;\n /** Whether bounded rediscovery/fallback executed. */\n rediscoveryExecuted: boolean;\n}\n\nexport interface QueryAttemptReference {\n sessionId: string;\n attemptId: string;\n}\n\n/** Public fork handle for creating a new attempt from a prior Query session. */\nexport interface QueryForkReference extends QueryAttemptReference {\n reason?: QueryAttemptForkReason;\n}\n\n/**\n * Public continuation state returned by headless Query responses.\n * Internal selected-tool lineage, Scout reuse, and clarification snapshots\n * remain durable server state but are not exposed as chat-style payloads.\n */\nexport interface QuerySessionState {\n sessionId: string;\n attemptId: string;\n parentAttemptId: string | null;\n rootAttemptId: string;\n mode: \"initial\" | \"resume\" | \"fork\";\n origin: \"initial_request\" | \"resume\" | \"fork\";\n status: \"active\" | \"completed\" | \"failed\" | \"aborted\";\n checkpoint: {\n currentStage: string | null;\n latestCheckpointArtifactId: string | null;\n canonicalDatasetId: string | null;\n executionProgramCurrentRevisionId: string | null;\n };\n}\n\nexport interface QueryResponseEnvelopeFact {\n id: string;\n label: string;\n path: string | null;\n relevanceScore: number | null;\n value: unknown;\n}\n\nexport interface QueryResponseEnvelopeSourceRef {\n id: string;\n provider: string | null;\n dataset: string | null;\n observedAt: string | null;\n publishedAt: string | null;\n artifactRef: string | null;\n url: string | null;\n note: string | null;\n}\n\nexport type QueryResponseEnvelopeTone =\n | \"positive\"\n | \"negative\"\n | \"neutral\"\n | \"caution\";\n\nexport type QueryControllerStopReason =\n | \"complete_answer\"\n | \"bounded_runtime_budget\"\n | \"bounded_same_endpoint_guardrail\"\n | \"bounded_upstream_abort_guardrail\"\n | \"clarification_required\"\n | \"capability_miss\";\n\nexport type QueryControllerIssueClass =\n | \"scope_ambiguity\"\n | \"missing_evidence\"\n | \"missing_capability\"\n | \"stale_data\"\n | \"wrong_tool_path\";\n\nexport type QueryControllerAction =\n | \"inspect_current_grounding\"\n | \"patch_current_program\"\n | \"bounded_rediscovery\"\n | \"clarify_scope\"\n | \"return_capability_miss\"\n | \"return_bounded_answer\"\n | \"return_complete_answer\";\n\nexport interface QueryResponseEnvelopeMarketAggregateFlow {\n netFlowUsd: number | null;\n grossInflowUsd: number | null;\n grossOutflowUsd: number | null;\n nativeNetFlow: number | null;\n nativeUnit: string | null;\n direction: \"inflow\" | \"outflow\" | \"flat\" | \"mixed\";\n}\n\nexport interface QueryResponseEnvelopeMarketVenueBreakdown {\n venue: string;\n asset: string | null;\n netFlowUsd: number | null;\n grossInflowUsd: number | null;\n grossOutflowUsd: number | null;\n nativeNetFlow: number | null;\n nativeUnit: string | null;\n shareOfTotal: number | null;\n rank: number | null;\n}\n\nexport interface QueryResponseEnvelopeCatalystRef {\n source: string;\n publishedAt: string | null;\n claim: string | null;\n relationToFlow: string | null;\n url: string | null;\n}\n\nexport interface QueryResponseEnvelopeDerivativesContext {\n openInterestDirection: string | null;\n openInterestChangePct: number | null;\n liquidationBias: string | null;\n venues: string[];\n relationshipToSpotFlows: string | null;\n}\n\nexport interface QueryResponseEnvelopeMarketIntelligence {\n asset: string | null;\n assets: string[] | null;\n timeWindow: string | null;\n asOf: string | null;\n aggregateFlow: QueryResponseEnvelopeMarketAggregateFlow | null;\n venueBreakdown: QueryResponseEnvelopeMarketVenueBreakdown[];\n catalystRefs: QueryResponseEnvelopeCatalystRef[];\n derivativesContext: QueryResponseEnvelopeDerivativesContext | null;\n}\n\nexport interface QueryResponseEnvelopeViewMetric {\n label: string;\n value: string;\n tone?: QueryResponseEnvelopeTone;\n}\n\nexport interface QueryResponseEnvelopeViewRow {\n key: string;\n cells: string[];\n tone?: QueryResponseEnvelopeTone;\n sourceRefIds?: string[];\n}\n\nexport interface QueryResponseEnvelope {\n responseShape: Exclude<QueryResponseShape, \"answer\">;\n response: string;\n summary: string;\n outcome: {\n label: string;\n tone: QueryResponseEnvelopeTone;\n stopReason: QueryControllerStopReason;\n issueClass: QueryControllerIssueClass | null;\n };\n controller: {\n scope: \"wedge\" | \"standard\";\n nextAction: QueryControllerAction;\n actionsTaken: QueryControllerAction[];\n patchFirstProgramPreserved: boolean;\n executionProgramRevisionId: string | null;\n hardBudgetApplied: boolean;\n } | null;\n evidence: {\n facts: QueryResponseEnvelopeFact[];\n sourceRefs: QueryResponseEnvelopeSourceRef[];\n assumptions: string[];\n knownUnknowns: string[];\n retrievalPlanReasonCodes: string[];\n marketIntelligence?: QueryResponseEnvelopeMarketIntelligence | null;\n };\n artifacts: {\n dataUrl: string | null;\n canonicalDataRef: {\n datasetId: string;\n hash: string;\n bytes: number;\n publicDataUrl: string | null;\n } | null;\n stageArtifactKinds: string[];\n };\n view: {\n type: QueryResponseEnvelopeViewType;\n label: string;\n title?: string | null;\n metrics?: QueryResponseEnvelopeViewMetric[];\n columns?: string[];\n rows?: QueryResponseEnvelopeViewRow[];\n } | null;\n freshness: {\n asOf: string | null;\n sourceTimestamps: string[];\n note: string;\n };\n confidence: {\n level: \"high\" | \"medium\" | \"low\";\n reason: string;\n verifiedFactCount: number;\n inferredFactCount: number;\n gapCount: number;\n gapSignals: Array<{\n code: string;\n severity: string;\n detail: string;\n }>;\n };\n usage: {\n durationMs: number;\n cost: QueryCost;\n toolsUsed: QueryToolUsage[];\n outcomeType: QueryOutcomeType;\n orchestrationMetrics?: QueryOrchestrationMetrics;\n };\n}\n\nexport interface QueryBaseResult {\n /** The answer text or machine-friendly summary returned for this query. */\n response: string;\n\n /** Tools that were used to answer the query */\n toolsUsed: QueryToolUsage[];\n\n /** Cost breakdown */\n cost: QueryCost;\n\n /** Total duration in milliseconds */\n durationMs: number;\n\n /** Optional execution data from tools (when includeData=true) */\n data?: unknown;\n\n /** Optional blob URL for persisted execution data (when includeDataUrl=true) */\n dataUrl?: string;\n\n /** Optional machine-readable Developer Mode trace payload */\n developerTrace?: QueryDeveloperTrace;\n\n /** Optional orchestration outcome metrics for benchmarking and rollout analysis */\n orchestrationMetrics?: QueryOrchestrationMetrics;\n\n /** Typed public stop reason for the final outcome. */\n stopReason?: QueryControllerStopReason;\n\n /** Typed issue class exposed by the bounded controller contract. */\n issueClass?: QueryControllerIssueClass | null;\n\n /** Ordered public controller actions taken before the final outcome. */\n actionsTaken?: QueryControllerAction[];\n\n /** Optional controller summary for bounded wedge-style answers. */\n controller?: QueryResponseEnvelope[\"controller\"];\n\n /**\n * Optional public durable continuation handles for resume/fork flows.\n * Query exposes handle-based continuation, not chat-style continuation payloads.\n */\n querySession?: QuerySessionState;\n}\n\n/**\n * The resolved result of a pay-per-response query\n */\nexport type QueryResult =\n | (QueryBaseResult &\n Partial<QueryResponseEnvelope> & {\n outcomeType: \"answer\";\n assumptionMade?: QueryAssumptionMetadata;\n })\n | (QueryBaseResult & {\n outcomeType: \"clarification_required\";\n clarification: QueryClarificationPayload;\n })\n | (QueryBaseResult & {\n outcomeType: \"capability_miss\";\n capabilityMiss: QueryCapabilityMissPayload;\n });\n\n/**\n * Successful response from the /api/v1/query endpoint\n */\nexport type QueryApiSuccessResponse = { success: true } & QueryResult;\n\n/**\n * Raw API response from the query endpoint\n */\nexport type QueryApiResponse = QueryApiSuccessResponse | ExecuteApiErrorResponse;\n\n// ---------------------------------------------------------------------------\n// Query stream event types\n// ---------------------------------------------------------------------------\n\n/** Emitted when a tool starts or changes execution status */\nexport interface QueryStreamToolStatusEvent {\n type: \"tool-status\";\n tool: { id: string; name: string };\n status: string;\n}\n\n/** Emitted for each chunk of the AI response text */\nexport interface QueryStreamTextDeltaEvent {\n type: \"text-delta\";\n delta: string;\n}\n\n/** Emitted when the server streams developer trace updates/chunks */\nexport interface QueryStreamDeveloperTraceEvent {\n type: \"developer-trace\";\n trace: QueryDeveloperTrace;\n}\n\n/** Emitted when the full response is complete */\nexport interface QueryStreamDoneEvent {\n type: \"done\";\n result: QueryResult;\n}\n\n/** Emitted when the server reports a recoverable or terminal query error */\nexport interface QueryStreamErrorEvent {\n type: \"error\";\n error: string;\n code?: ContextErrorCode | string;\n scope?: string;\n reasonCode?: string;\n outcomeType?: Exclude<QueryOutcomeType, \"answer\">;\n clarification?: QueryClarificationPayload;\n capabilityMiss?: QueryCapabilityMissPayload;\n querySession?: QuerySessionState;\n}\n\n/**\n * Union of all events emitted during a streaming query\n */\nexport type QueryStreamEvent =\n | QueryStreamToolStatusEvent\n | QueryStreamTextDeltaEvent\n | QueryStreamDeveloperTraceEvent\n | QueryStreamDoneEvent\n | QueryStreamErrorEvent;\n\n// ---------------------------------------------------------------------------\n// Error types\n// ---------------------------------------------------------------------------\n\n/**\n * Specific error codes returned by the Context Protocol API\n */\nexport type ContextErrorCode =\n | \"unauthorized\"\n | \"no_wallet\"\n | \"insufficient_allowance\"\n | \"payment_failed\"\n | \"execution_failed\"\n | \"query_failed\"\n | \"invalid_tool_method\"\n | \"method_not_execute_eligible\"\n | \"invalid_max_spend\"\n | \"session_not_found\"\n | \"session_forbidden\"\n | \"session_closed\"\n | \"session_expired\"\n | \"max_spend_mismatch\"\n | \"session_budget_exceeded\";\n\n/**\n * Error thrown by the Context Protocol client\n */\nexport class ContextError extends Error {\n constructor(\n message: string,\n public readonly code?: ContextErrorCode | string,\n public readonly statusCode?: number,\n public readonly helpUrl?: string\n ) {\n super(message);\n this.name = \"ContextError\";\n Object.setPrototypeOf(this, ContextError.prototype);\n }\n}\n","import type { UpdateToolOptions, UpdateToolResult } from \"../types.js\";\nimport { ALLOWED_TOOL_CATEGORIES, ContextError } from \"../types.js\";\nimport type { ContextClient } from \"../client.js\";\n\n/**\n * Developer resource for managing tool listings on the Context Protocol marketplace.\n *\n * Scoped to contributor/developer concerns (listing management), separate from\n * the consumer-facing `tools.execute()` and `query.run()`.\n */\nexport class Developer {\n constructor(private client: ContextClient) {}\n\n /**\n * Update a tool listing's metadata (name, description, category).\n *\n * Requires an API key belonging to the tool's owner.\n *\n * @param toolId - The UUID of the tool to update\n * @param updates - Fields to update (at least one required)\n * @returns The updated tool metadata\n *\n * @throws {ContextError} If authentication fails or the caller does not own the tool\n *\n * @example\n * ```typescript\n * const updated = await client.developer.updateTool(\"tool-uuid\", {\n * description: \"Updated description with better showcase prompts\",\n * category: \"crypto\",\n * });\n * console.log(updated.updatedAt);\n * ```\n */\n async updateTool(\n toolId: string,\n updates: UpdateToolOptions\n ): Promise<UpdateToolResult> {\n if (!toolId) {\n throw new ContextError(\"toolId is required\");\n }\n\n if (\n updates.name === undefined &&\n updates.description === undefined &&\n updates.category === undefined\n ) {\n throw new ContextError(\n \"At least one field required: name, description, or category\"\n );\n }\n\n if (\n updates.category !== undefined &&\n updates.category !== null &&\n !ALLOWED_TOOL_CATEGORIES.includes(updates.category)\n ) {\n throw new ContextError(\n `category must be one of: ${ALLOWED_TOOL_CATEGORIES.join(\", \")}`\n );\n }\n\n const encodedToolId = encodeURIComponent(toolId);\n\n return this.client._fetch<UpdateToolResult>(\n `/api/v1/tools/${encodedToolId}`,\n {\n method: \"PATCH\",\n body: JSON.stringify(updates),\n },\n { retry: false }\n );\n }\n}\n","import type { SearchOptions, SearchResponse, Tool } from \"../types.js\";\nimport type { ContextClient } from \"../client.js\";\n\n/**\n * Discovery resource for searching and finding tools on the Context Protocol marketplace\n */\nexport class Discovery {\n constructor(private client: ContextClient) {}\n\n /**\n * Fetch a single marketplace tool by its unique ID.\n */\n async get(toolId: string): Promise<Tool> {\n return this.client._fetch<Tool>(\n `/api/v1/tools/${encodeURIComponent(toolId)}`\n );\n }\n\n /**\n * Search for tools matching a query string.\n *\n * Backward-compatible signatures:\n * - `search(\"gas prices\", 10)`\n * - `search({ query: \"gas prices\", limit: 10, mode: \"execute\" })`\n */\n async search(query: string, limit?: number): Promise<Tool[]>;\n async search(options: SearchOptions): Promise<Tool[]>;\n async search(\n queryOrOptions: string | SearchOptions,\n limit?: number\n ): Promise<Tool[]> {\n const options: SearchOptions =\n typeof queryOrOptions === \"string\"\n ? { query: queryOrOptions, limit }\n : queryOrOptions;\n\n const params = new URLSearchParams();\n const query = options.query ?? \"\";\n\n if (query) {\n params.set(\"q\", query);\n }\n\n if (options.limit !== undefined) {\n params.set(\"limit\", String(options.limit));\n }\n\n if (options.mode) {\n params.set(\"mode\", options.mode);\n }\n\n if (options.surface) {\n params.set(\"surface\", options.surface);\n }\n\n if (options.queryEligible !== undefined) {\n params.set(\"queryEligible\", String(options.queryEligible));\n }\n\n if (options.requireExecutePricing !== undefined) {\n params.set(\n \"requireExecutePricing\",\n String(options.requireExecutePricing)\n );\n }\n\n if (\n options.excludeLatencyClasses &&\n options.excludeLatencyClasses.length > 0\n ) {\n params.set(\"excludeLatency\", options.excludeLatencyClasses.join(\",\"));\n }\n\n if (options.excludeSlow !== undefined) {\n params.set(\"excludeSlow\", String(options.excludeSlow));\n }\n\n if (options.favoritesOnly !== undefined) {\n params.set(\"favorites_only\", String(options.favoritesOnly));\n }\n\n const queryString = params.toString();\n const endpoint = `/api/v1/tools/search${queryString ? `?${queryString}` : \"\"}`;\n\n const response = await this.client._fetch<SearchResponse>(endpoint);\n\n return response.tools;\n }\n\n /**\n * Get featured/popular tools (empty query search)\n *\n * @param limit - Maximum number of results (1-50, default 10)\n * @returns Array of featured tools\n *\n * @example\n * ```typescript\n * const featured = await client.discovery.getFeatured(5);\n * ```\n */\n async getFeatured(\n limit?: number,\n options?: Omit<SearchOptions, \"query\" | \"limit\">\n ): Promise<Tool[]> {\n return this.search({\n ...(options ?? {}),\n query: \"\",\n ...(limit !== undefined ? { limit } : {}),\n });\n }\n}\n","import type {\n ExecuteOptions,\n ExecuteApiResponse,\n ExecuteSessionApiResponse,\n ExecuteSessionResult,\n ExecuteSessionStartOptions,\n ExecutionResult,\n} from \"../types.js\";\nimport { ContextError } from \"../types.js\";\nimport type { ContextClient } from \"../client.js\";\n\n/**\n * Tools resource for executing tools on the Context Protocol marketplace\n */\nexport class Tools {\n constructor(private client: ContextClient) {}\n\n /**\n * Execute a tool with the provided arguments\n *\n * @param options - Execution options\n * @param options.toolId - The UUID of the tool (from search results)\n * @param options.toolName - The specific MCP tool method to call (from tool's mcpTools array)\n * @param options.args - Arguments to pass to the tool\n * @returns The execution result with the tool's output data\n *\n * @throws {ContextError} With code `no_wallet` if wallet not set up\n * @throws {ContextError} With code `insufficient_allowance` if spending cap not set\n * @throws {ContextError} With code `payment_failed` if payment settlement fails\n * @throws {ContextError} With code `execution_failed` if tool execution fails\n *\n * @example\n * ```typescript\n * // First, search for a tool\n * const tools = await client.discovery.search(\"gas prices\");\n * const tool = tools[0];\n *\n * // Execute a specific method from the tool's mcpTools\n * const result = await client.tools.execute({\n * toolId: tool.id,\n * toolName: tool.mcpTools[0].name, // e.g., \"get_gas_prices\"\n * args: { chainId: 1 }\n * });\n *\n * console.log(result.result); // The tool's output\n * console.log(result.durationMs); // Execution time\n * ```\n */\n async execute<T = unknown>(options: ExecuteOptions): Promise<ExecutionResult<T>> {\n const {\n toolId,\n toolName,\n args,\n idempotencyKey,\n mode,\n sessionId,\n maxSpendUsd,\n closeSession,\n } = options;\n const headers = idempotencyKey\n ? { \"Idempotency-Key\": idempotencyKey }\n : undefined;\n\n const response = await this.client._fetch<ExecuteApiResponse>(\n \"/api/v1/tools/execute\",\n {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n toolId,\n toolName,\n args,\n mode: mode ?? \"execute\",\n sessionId,\n maxSpendUsd,\n closeSession,\n }),\n }\n );\n\n // Handle error response\n if (\"error\" in response) {\n throw new ContextError(\n response.error,\n response.code,\n undefined, // Don't hardcode - this was a 200 OK with error body\n response.helpUrl\n );\n }\n\n // Handle success response\n if (response.success) {\n return {\n mode: response.mode,\n result: response.result as T,\n tool: response.tool,\n method: response.method,\n session: response.session,\n durationMs: response.durationMs,\n };\n }\n\n // Fallback - shouldn't reach here with valid API responses\n throw new ContextError(\"Unexpected response format from API\");\n }\n\n /**\n * Start an execute session with a max spend budget.\n */\n async startSession(\n options: ExecuteSessionStartOptions\n ): Promise<ExecuteSessionResult> {\n const response = await this.client._fetch<ExecuteSessionApiResponse>(\n \"/api/v1/tools/execute/sessions\",\n {\n method: \"POST\",\n body: JSON.stringify({\n mode: \"execute\",\n maxSpendUsd: options.maxSpendUsd,\n }),\n }\n );\n\n return this.resolveSessionLifecycleResponse(response);\n }\n\n /**\n * Fetch current execute session status by ID.\n */\n async getSession(sessionId: string): Promise<ExecuteSessionResult> {\n if (!sessionId) {\n throw new ContextError(\"sessionId is required\");\n }\n\n const encodedSessionId = encodeURIComponent(sessionId);\n const response = await this.client._fetch<ExecuteSessionApiResponse>(\n `/api/v1/tools/execute/sessions/${encodedSessionId}`\n );\n\n return this.resolveSessionLifecycleResponse(response);\n }\n\n /**\n * Close an execute session by ID.\n */\n async closeSession(sessionId: string): Promise<ExecuteSessionResult> {\n if (!sessionId) {\n throw new ContextError(\"sessionId is required\");\n }\n\n const encodedSessionId = encodeURIComponent(sessionId);\n const response = await this.client._fetch<ExecuteSessionApiResponse>(\n `/api/v1/tools/execute/sessions/${encodedSessionId}/close`,\n {\n method: \"POST\",\n body: JSON.stringify({ mode: \"execute\" }),\n }\n );\n\n return this.resolveSessionLifecycleResponse(response);\n }\n\n private resolveSessionLifecycleResponse(\n response: ExecuteSessionApiResponse\n ): ExecuteSessionResult {\n if (\"error\" in response) {\n throw new ContextError(\n response.error,\n response.code,\n undefined,\n response.helpUrl\n );\n }\n\n if (response.success) {\n return {\n mode: response.mode,\n session: response.session,\n };\n }\n\n throw new ContextError(\"Unexpected response format from API\");\n }\n}\n","import type {\n QueryCapabilityMissPayload,\n QueryClarificationPayload,\n QueryClarificationPolicy,\n QueryOptions,\n QueryDeveloperTrace,\n QueryResult,\n QueryStreamEvent,\n} from \"../types.js\";\nimport { ContextError } from \"../types.js\";\nimport type { ContextClient } from \"../client.js\";\n\n/**\n * Query resource for pay-per-response agentic queries.\n *\n * Unlike `tools.execute()` which calls a single tool once (pay-per-request),\n * the Query resource sends a natural-language question and lets the server\n * handle the live librarian pipeline (`discover -> select -> metadata scout ->\n * clarify if needed -> iterative execute -> synthesize -> settle`) plus AI\n * synthesis — all for one flat fee.\n *\n * This is the \"prepared meal\" vs \"raw ingredients\" distinction:\n * - `tools.execute()` = raw data, full control, predictable cost\n * - `query.run()` / `query.stream()` = curated intelligence, one payment\n */\nexport class Query {\n constructor(private client: ContextClient) {}\n\n private normalizeResult(result: QueryResult): QueryResult {\n const candidate = result as QueryResult & { outcomeType?: string };\n if (\n candidate.outcomeType === \"clarification_required\" &&\n \"clarification\" in candidate &&\n candidate.clarification\n ) {\n return candidate;\n }\n if (\n candidate.outcomeType === \"capability_miss\" &&\n \"capabilityMiss\" in candidate &&\n candidate.capabilityMiss\n ) {\n return candidate;\n }\n return {\n ...candidate,\n outcomeType: \"answer\",\n };\n }\n\n private buildPolicyErrorEvent(params: {\n result: QueryResult;\n clarificationPolicy?: QueryClarificationPolicy;\n }):\n | {\n type: \"error\";\n error: string;\n code: string;\n reasonCode: string;\n outcomeType: \"clarification_required\" | \"capability_miss\";\n clarification?: QueryClarificationPayload;\n capabilityMiss?: QueryCapabilityMissPayload;\n querySession?: QueryResult[\"querySession\"];\n }\n | undefined {\n if (params.clarificationPolicy !== \"error\") {\n return;\n }\n\n if (params.result.outcomeType === \"clarification_required\") {\n return {\n type: \"error\",\n error: params.result.response,\n code: \"clarification_required\",\n reasonCode: \"clarification_required\",\n outcomeType: \"clarification_required\",\n clarification: params.result.clarification,\n querySession: params.result.querySession,\n };\n }\n\n if (params.result.outcomeType === \"capability_miss\") {\n return {\n type: \"error\",\n error: params.result.response,\n code: \"capability_miss\",\n reasonCode: \"capability_miss\",\n outcomeType: \"capability_miss\",\n capabilityMiss: params.result.capabilityMiss,\n querySession: params.result.querySession,\n };\n }\n\n return undefined;\n }\n\n private buildSyntheticTraceFromRunResult(params: {\n toolsUsed: Array<{ id: string; name: string; skillCalls: number }>;\n durationMs: number;\n }): QueryDeveloperTrace {\n const timeline = params.toolsUsed.map((tool, index) => ({\n stepType: \"tool-call\",\n event: \"tool-call\",\n status: \"success\",\n timestampMs: index,\n tool: {\n id: tool.id,\n name: tool.name,\n },\n metadata: {\n skillCalls: tool.skillCalls,\n synthetic: true,\n },\n }));\n\n const toolCalls = params.toolsUsed.reduce(\n (sum, tool) => sum + Math.max(tool.skillCalls, 0),\n 0\n );\n\n return {\n summary: {\n toolCalls,\n retryCount: 0,\n selfHealCount: 0,\n fallbackCount: 0,\n failureCount: 0,\n recoveryCount: 0,\n completionChecks: 0,\n loopCount: 0,\n },\n timeline,\n source: \"sdk-fallback\",\n synthetic: true,\n reason: \"backend_trace_missing\",\n durationMs: params.durationMs,\n };\n }\n\n private buildSyntheticTraceFromStreamStatus(params: {\n statusTimeline: Array<{\n status: string;\n tool: { id: string; name: string };\n }>;\n toolsUsed: Array<{ id: string; name: string; skillCalls: number }>;\n durationMs: number;\n }): QueryDeveloperTrace {\n const timeline = params.statusTimeline.map((entry, index) => ({\n stepType: \"tool-status\",\n event: \"tool-status\",\n status: entry.status,\n timestampMs: index,\n tool:\n entry.tool.name || entry.tool.id\n ? {\n id: entry.tool.id || undefined,\n name: entry.tool.name || undefined,\n }\n : undefined,\n metadata: { synthetic: true },\n }));\n\n const toolCallsFromUsage = params.toolsUsed.reduce(\n (sum, tool) => sum + Math.max(tool.skillCalls, 0),\n 0\n );\n const toolCallsFromStatus = params.statusTimeline.filter(\n (entry) => entry.status === \"tool-complete\"\n ).length;\n const toolCalls = toolCallsFromUsage > 0 ? toolCallsFromUsage : toolCallsFromStatus;\n\n const retryCount = params.statusTimeline.filter((entry) =>\n /(retry|fix|reflect|recover)/i.test(entry.status)\n ).length;\n const completionChecks = params.statusTimeline.filter((entry) =>\n /complet/i.test(entry.status)\n ).length;\n\n return {\n summary: {\n toolCalls,\n retryCount,\n selfHealCount: retryCount,\n fallbackCount: 0,\n failureCount: 0,\n recoveryCount: 0,\n completionChecks,\n loopCount: retryCount,\n },\n timeline,\n source: \"sdk-fallback\",\n synthetic: true,\n reason: \"backend_trace_missing\",\n durationMs: params.durationMs,\n };\n }\n\n private mergeDeveloperTrace(\n first: QueryDeveloperTrace | undefined,\n second: QueryDeveloperTrace | undefined\n ): QueryDeveloperTrace | undefined {\n if (!first) return second;\n if (!second) return first;\n\n const firstTimeline = Array.isArray(first.timeline) ? first.timeline : [];\n const secondTimeline = Array.isArray(second.timeline) ? second.timeline : [];\n const mergedTimeline = [...firstTimeline, ...secondTimeline];\n\n return {\n ...first,\n ...second,\n summary: {\n ...(typeof first.summary === \"object\" && first.summary ? first.summary : {}),\n ...(typeof second.summary === \"object\" && second.summary\n ? second.summary\n : {}),\n },\n ...(mergedTimeline.length > 0 ? { timeline: mergedTimeline } : {}),\n };\n }\n\n private parseStreamEvent(rawData: string): QueryStreamEvent | undefined {\n const parsed = JSON.parse(rawData) as unknown;\n if (!parsed || typeof parsed !== \"object\") {\n return undefined;\n }\n\n const event = parsed as QueryStreamEvent;\n if (typeof (event as { type?: unknown }).type !== \"string\") {\n return undefined;\n }\n\n return event;\n }\n\n /**\n * Run an agentic query and wait for the full response.\n *\n * The server discovers relevant tools (or uses the ones you specify),\n * executes the discovery-first pipeline (up to 100 MCP calls per tool),\n * and returns an AI-synthesized answer. Payment is settled after\n * successful execution via deferred settlement.\n *\n * @param options - Query options or a plain string question\n * @returns The complete query result with response text, tools used, and cost\n *\n * @throws {ContextError} With code `no_wallet` if wallet not set up\n * @throws {ContextError} With code `insufficient_allowance` if spending cap not set\n * @throws {ContextError} With code `payment_failed` if payment settlement fails\n * @throws {ContextError} With code `execution_failed` if the agentic pipeline fails\n *\n * @example\n * ```typescript\n * // Simple question — server discovers tools automatically\n * const answer = await client.query.run(\"What are the top whale movements on Base?\");\n * console.log(answer.response); // AI-synthesized answer\n * console.log(answer.toolsUsed); // Which tools were used\n * console.log(answer.cost); // Cost breakdown\n *\n * // With specific tools (Manual Mode)\n * const answer = await client.query.run({\n * query: \"Analyze whale activity\",\n * tools: [\"tool-uuid-1\", \"tool-uuid-2\"],\n * });\n * ```\n */\n async run(options: QueryOptions | string): Promise<QueryResult> {\n const opts = typeof options === \"string\" ? { query: options } : options;\n let terminalError:\n | { error: string; code?: string; scope?: string; reasonCode?: string }\n | undefined;\n let finalResult: QueryResult | undefined;\n\n for await (const event of this.stream(opts)) {\n if (event.type === \"error\") {\n terminalError = {\n error: event.error,\n ...(event.code ? { code: event.code } : {}),\n ...(event.scope ? { scope: event.scope } : {}),\n ...(event.reasonCode ? { reasonCode: event.reasonCode } : {}),\n };\n continue;\n }\n\n if (event.type === \"done\") {\n finalResult = event.result;\n }\n }\n\n if (finalResult) {\n return finalResult;\n }\n\n if (terminalError) {\n throw new ContextError(terminalError.error, terminalError.code);\n }\n\n throw new ContextError(\"Streaming query ended before done event\");\n }\n\n /**\n * Run an agentic query with streaming. Returns an async iterable that\n * yields events as the server processes the query in real-time.\n *\n * Event types:\n * - `tool-status` — A tool started executing or changed status\n * - `text-delta` — A chunk of the AI response text\n * - `developer-trace` — Runtime trace metadata (when includeDeveloperTrace=true)\n * - `error` — A structured query/runtime error emitted before stream completion\n * - `done` — The full response is complete (includes final `QueryResult`)\n *\n * @param options - Query options or a plain string question\n * @returns An async iterable of stream events\n *\n * @example\n * ```typescript\n * for await (const event of client.query.stream(\"What are the top whale movements?\")) {\n * switch (event.type) {\n * case \"tool-status\":\n * console.log(`Tool ${event.tool.name}: ${event.status}`);\n * break;\n * case \"text-delta\":\n * process.stdout.write(event.delta);\n * break;\n * case \"developer-trace\":\n * console.log(\"Trace summary:\", event.trace.summary);\n * break;\n * case \"done\":\n * console.log(\"\\nCost:\", event.result.cost.totalCostUsd);\n * break;\n * case \"error\":\n * console.error(\"Stream error:\", event.error);\n * break;\n * }\n * }\n * ```\n */\n async *stream(\n options: QueryOptions | string\n ): AsyncGenerator<QueryStreamEvent> {\n const opts = typeof options === \"string\" ? { query: options } : options;\n const headers = opts.idempotencyKey\n ? { \"Idempotency-Key\": opts.idempotencyKey }\n : undefined;\n\n const response = await this.client._fetchRaw(\"/api/v1/query\", {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n query: opts.query,\n tools: opts.tools,\n resumeFrom: opts.resumeFrom,\n forkFrom: opts.forkFrom,\n clarificationPolicy: opts.clarificationPolicy,\n answerModelId: opts.answerModelId,\n responseShape: opts.responseShape,\n favoritesOnly: opts.favoritesOnly,\n includeData: opts.includeData,\n includeDataUrl: opts.includeDataUrl,\n includeDeveloperTrace: opts.includeDeveloperTrace,\n stream: true,\n }),\n });\n\n const body = response.body;\n if (!body) {\n throw new ContextError(\"No response body for streaming query\");\n }\n\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n let aggregatedTrace: QueryDeveloperTrace | undefined;\n const statusTimeline: Array<{\n status: string;\n tool: { id: string; name: string };\n }> = [];\n\n const parseAndHydrateEvent = (\n rawData: string\n ): QueryStreamEvent | undefined => {\n const event = this.parseStreamEvent(rawData);\n if (!event) {\n return undefined;\n }\n\n if (event.type === \"developer-trace\") {\n aggregatedTrace = this.mergeDeveloperTrace(aggregatedTrace, event.trace);\n return event;\n }\n\n if (event.type === \"tool-status\") {\n statusTimeline.push({\n status: event.status,\n tool: {\n id: event.tool.id,\n name: event.tool.name,\n },\n });\n return event;\n }\n\n if (event.type === \"done\") {\n const normalizedResult = this.normalizeResult(event.result);\n let mergedTrace = this.mergeDeveloperTrace(\n aggregatedTrace,\n normalizedResult.developerTrace\n );\n if (!mergedTrace && opts.includeDeveloperTrace) {\n mergedTrace =\n statusTimeline.length > 0\n ? this.buildSyntheticTraceFromStreamStatus({\n statusTimeline,\n toolsUsed: normalizedResult.toolsUsed,\n durationMs: normalizedResult.durationMs,\n })\n : this.buildSyntheticTraceFromRunResult({\n toolsUsed: normalizedResult.toolsUsed,\n durationMs: normalizedResult.durationMs,\n });\n }\n if (mergedTrace) {\n normalizedResult.developerTrace = mergedTrace;\n }\n event.result = normalizedResult;\n\n const policyErrorEvent = this.buildPolicyErrorEvent({\n result: normalizedResult,\n clarificationPolicy: opts.clarificationPolicy,\n });\n if (policyErrorEvent) {\n return policyErrorEvent;\n }\n }\n\n return event;\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.startsWith(\"data: \")) {\n const data = trimmed.slice(6);\n if (data === \"[DONE]\") return;\n try {\n const event = parseAndHydrateEvent(data);\n if (event) {\n yield event;\n }\n } catch {\n // Skip malformed SSE events\n }\n }\n }\n }\n\n // Process any remaining buffer\n if (buffer.trim().startsWith(\"data: \")) {\n const data = buffer.trim().slice(6);\n if (data !== \"[DONE]\") {\n try {\n const event = parseAndHydrateEvent(data);\n if (event) {\n yield event;\n }\n } catch {\n // Skip malformed SSE events\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n}\n","import type { ContextClientOptions } from \"./types.js\";\nimport { ContextError } from \"./types.js\";\nimport { Developer } from \"./resources/developer.js\";\nimport { Discovery } from \"./resources/discovery.js\";\nimport { Tools } from \"./resources/tools.js\";\nimport { Query } from \"./resources/query.js\";\n\nconst DEFAULT_BASE_URL = \"https://www.ctxprotocol.com\";\nconst DEFAULT_REQUEST_TIMEOUT_MS = 300_000;\nconst DEFAULT_STREAM_TIMEOUT_MS = 600_000;\n\n/**\n * The official TypeScript client for the Context Protocol.\n *\n * Use this client to discover and execute AI tools programmatically.\n *\n * @example\n * ```typescript\n * import { ContextClient } from \"@contextprotocol/client\";\n *\n * const client = new ContextClient({\n * apiKey: \"sk_live_...\"\n * });\n *\n * // Pay-per-request: Execute a specific tool\n * const result = await client.tools.execute({\n * toolId: \"tool-uuid\",\n * toolName: \"get_gas_prices\",\n * args: { chainId: 1 }\n * });\n *\n * // Pay-per-response: Ask a question, get a curated answer\n * const answer = await client.query.run(\"What are the top whale movements on Base?\");\n * console.log(answer.response);\n * ```\n */\nexport class ContextClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly requestTimeoutMs: number;\n private readonly streamTimeoutMs: number;\n private _closed = false;\n\n /**\n * Developer resource for managing tool listings (contributor/developer concerns).\n */\n public readonly developer: Developer;\n\n /**\n * Discovery resource for searching tools\n */\n public readonly discovery: Discovery;\n\n /**\n * Tools resource for executing tools (pay-per-request)\n */\n public readonly tools: Tools;\n\n /**\n * Query resource for agentic queries (pay-per-response).\n *\n * Unlike `tools.execute()` which calls a single tool once, `query` sends\n * a natural-language question and lets the server handle discovery,\n * metadata scout, clarification, iterative execution, and AI synthesis —\n * one flat fee.\n */\n public readonly query: Query;\n\n /**\n * Creates a new Context Protocol client\n *\n * @param options - Client configuration options\n * @param options.apiKey - Your Context Protocol API key (format: sk_live_...)\n * @param options.baseUrl - Optional base URL override (defaults to https://www.ctxprotocol.com)\n * @param options.requestTimeoutMs - Optional timeout for non-streaming requests (default 300000ms)\n * @param options.streamTimeoutMs - Optional timeout for establishing stream requests (default 600000ms)\n */\n constructor(options: ContextClientOptions) {\n if (!options.apiKey) {\n throw new ContextError(\"API key is required\");\n }\n\n const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n const streamTimeoutMs = options.streamTimeoutMs ?? DEFAULT_STREAM_TIMEOUT_MS;\n\n if (!Number.isFinite(requestTimeoutMs) || requestTimeoutMs <= 0) {\n throw new ContextError(\"requestTimeoutMs must be a positive number\");\n }\n\n if (!Number.isFinite(streamTimeoutMs) || streamTimeoutMs <= 0) {\n throw new ContextError(\"streamTimeoutMs must be a positive number\");\n }\n\n this.apiKey = options.apiKey;\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n this.requestTimeoutMs = requestTimeoutMs;\n this.streamTimeoutMs = streamTimeoutMs;\n\n // Initialize resources\n this.developer = new Developer(this);\n this.discovery = new Discovery(this);\n this.tools = new Tools(this);\n this.query = new Query(this);\n }\n\n /**\n * Close the client and clean up resources.\n * After calling close(), any in-flight requests may be aborted.\n */\n close(): void {\n this._closed = true;\n }\n\n /**\n * Internal method for making authenticated HTTP requests\n * Includes timeout and retry with exponential backoff for transient errors\n *\n * @internal\n */\n async _fetch<T>(\n endpoint: string,\n options: RequestInit = {},\n fetchOptions?: { retry?: boolean }\n ): Promise<T> {\n if (this._closed) {\n throw new ContextError(\"Client has been closed\");\n }\n\n const url = `${this.baseUrl}${endpoint}`;\n const maxRetries = 3;\n const timeoutMs = this.requestTimeoutMs;\n const method = (options.method ?? \"GET\").toUpperCase();\n const requestHeaders = new Headers(options.headers);\n const canRetryRequest =\n fetchOptions?.retry === false\n ? false\n : method === \"GET\" ||\n method === \"HEAD\" ||\n method === \"OPTIONS\" ||\n requestHeaders.has(\"Idempotency-Key\");\n\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n const mergedHeaders = new Headers(requestHeaders);\n if (!mergedHeaders.has(\"Content-Type\")) {\n mergedHeaders.set(\"Content-Type\", \"application/json\");\n }\n mergedHeaders.set(\"Authorization\", `Bearer ${this.apiKey}`);\n\n try {\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n headers: mergedHeaders,\n });\n\n clearTimeout(timeout);\n\n if (!response.ok) {\n // Retry on 5xx server errors\n if (response.status >= 500 && canRetryRequest && attempt < maxRetries) {\n const delay = Math.min(1000 * 2 ** attempt, 10_000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n continue;\n }\n\n let errorMessage = `HTTP ${response.status}: ${response.statusText}`;\n let errorCode: string | undefined;\n let helpUrl: string | undefined;\n\n try {\n const errorBody = await response.json();\n if (errorBody.error) {\n errorMessage = errorBody.error;\n errorCode = errorBody.code;\n helpUrl = errorBody.helpUrl;\n }\n } catch {\n // Use default error message if JSON parsing fails\n }\n\n throw new ContextError(errorMessage, errorCode, response.status, helpUrl);\n }\n\n try {\n return (await response.json()) as T;\n } catch (error) {\n const parseError = error instanceof Error ? error : new Error(String(error));\n throw new ContextError(\n `Failed to parse JSON response: ${parseError.message}`,\n undefined,\n response.status\n );\n }\n } catch (error) {\n clearTimeout(timeout);\n\n if (error instanceof ContextError) {\n throw error;\n }\n\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Retry on network errors and timeouts\n const isRetryable =\n lastError.name === \"AbortError\" ||\n lastError.message.includes(\"fetch failed\") ||\n lastError.message.includes(\"ECONNRESET\") ||\n lastError.message.includes(\"ETIMEDOUT\");\n\n if (isRetryable && canRetryRequest && attempt < maxRetries) {\n const delay = Math.min(1000 * 2 ** attempt, 10_000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n continue;\n }\n\n if (lastError.name === \"AbortError\") {\n throw new ContextError(\n `Request timed out after ${timeoutMs / 1000}s`,\n undefined,\n 408\n );\n }\n\n throw new ContextError(\n lastError.message,\n undefined,\n undefined\n );\n }\n }\n\n throw lastError ?? new ContextError(\"Request failed after retries\");\n }\n\n /**\n * Internal method for making authenticated HTTP requests that returns\n * the raw Response object. Used for streaming endpoints (SSE).\n * Includes a configurable timeout for stream setup.\n *\n * @internal\n */\n async _fetchRaw(endpoint: string, options: RequestInit = {}): Promise<Response> {\n if (this._closed) {\n throw new ContextError(\"Client has been closed\");\n }\n\n const url = `${this.baseUrl}${endpoint}`;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.streamTimeoutMs);\n\n let response: Response;\n try {\n response = await fetch(url, {\n ...options,\n signal: controller.signal,\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n ...options.headers,\n },\n });\n } catch (error) {\n clearTimeout(timeout);\n const lastError = error instanceof Error ? error : new Error(String(error));\n if (lastError.name === \"AbortError\") {\n throw new ContextError(\n `Streaming request timed out after ${this.streamTimeoutMs / 1000}s`,\n undefined,\n 408\n );\n }\n throw new ContextError(lastError.message);\n }\n\n clearTimeout(timeout);\n\n if (!response.ok) {\n let errorMessage = `HTTP ${response.status}: ${response.statusText}`;\n let errorCode: string | undefined;\n let helpUrl: string | undefined;\n\n try {\n const errorBody = await response.json();\n if (errorBody.error) {\n errorMessage = errorBody.error;\n errorCode = errorBody.code;\n helpUrl = errorBody.helpUrl;\n }\n } catch {\n // Use default error message if JSON parsing fails\n }\n\n throw new ContextError(errorMessage, errorCode, response.status, helpUrl);\n }\n\n return response;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/client/types.ts","../../src/client/resources/developer.ts","../../src/client/resources/discovery.ts","../../src/client/resources/tools.ts","../../src/client/resources/query.ts","../../src/client/client.ts"],"names":[],"mappings":";;;AAmRO,IAAM,uBAAA,GAA0B;AAAA,EACrC,eAAA;AAAA,EACA,mBAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA,EACA,oBAAA;AAAA,EACA,YAAA;AAAA,EACA,iBAAA;AAAA,EACA,qBAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF;AAwkCO,IAAM,YAAA,GAAN,MAAM,aAAA,SAAqB,KAAA,CAAM;AAAA,EACtC,WAAA,CACE,OAAA,EACgB,IAAA,EACA,UAAA,EACA,OAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAJG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,C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CAAS,MAAM,CAAA,EAAA,EAAK,SAAS,UAAU,CAAA,CAAA;AAClE,MAAA,IAAI,SAAA;AACJ,MAAA,IAAI,OAAA;AAEJ,MAAA,IAAI;AACF,QAAA,MAAM,SAAA,GAAY,MAAM,QAAA,CAAS,IAAA,EAAK;AACtC,QAAA,IAAI,UAAU,KAAA,EAAO;AACnB,UAAA,YAAA,GAAe,SAAA,CAAU,KAAA;AACzB,UAAA,SAAA,GAAY,SAAA,CAAU,IAAA;AACtB,UAAA,OAAA,GAAU,SAAA,CAAU,OAAA;AAAA,QACtB;AAAA,MACF,CAAA,CAAA,MAAQ;AAAA,MAER;AAEA,MAAA,MAAM,IAAI,YAAA,CAAa,YAAA,EAAc,SAAA,EAAW,QAAA,CAAS,QAAQ,OAAO,CAAA;AAAA,IAC1E;AAEA,IAAA,OAAO,QAAA;AAAA,EACT;AACF","file":"index.cjs","sourcesContent":["import type { ContributorSearchTraceRecord } from \"../contrib/search/types.js\";\n\n/**\n * Configuration options for initializing the ContextClient\n */\nexport interface ContextClientOptions {\n /**\n * Your Context Protocol API key\n * @example \"sk_live_abc123...\"\n */\n apiKey: string;\n\n /**\n * Base URL for the Context Protocol API\n * @default \"https://www.ctxprotocol.com\"\n */\n baseUrl?: string;\n\n /**\n * Request timeout for non-streaming API calls in milliseconds.\n * @default 300000\n */\n requestTimeoutMs?: number;\n\n /**\n * Request timeout for establishing streaming API calls in milliseconds.\n * @default 600000\n */\n streamTimeoutMs?: number;\n}\n\n/**\n * An individual MCP tool exposed by a tool listing\n */\nexport interface McpToolRateLimitHints {\n /** Suggested request budget for this method */\n maxRequestsPerMinute?: number;\n\n /** Suggested parallel call ceiling for this method */\n maxConcurrency?: number;\n\n /** Suggested minimum delay between sequential calls */\n cooldownMs?: number;\n\n /** Whether this method already supports bulk/batch retrieval */\n supportsBulk?: boolean;\n\n /** Preferred batch-oriented methods to call instead of fan-out loops */\n recommendedBatchTools?: string[];\n\n /** Optional human-readable notes for execution behavior */\n notes?: string;\n}\n\nexport type DiscoveryMode = \"query\" | \"execute\";\nexport type McpToolSurface = \"answer\" | \"execute\" | \"both\";\nexport type McpToolLatencyClass = \"instant\" | \"fast\" | \"slow\" | \"streaming\";\nexport type SuggestedPromptSource = \"contributor\" | \"platform\" | \"sdk\";\n\nexport interface SuggestedPrompt {\n /** Prompt text shown as a clickable example in the Context app */\n text: string;\n\n /** Where this prompt came from */\n source: SuggestedPromptSource;\n\n /** Optional display hint for the listing price */\n priceHint?: string;\n}\n\nexport interface McpToolPricingMeta {\n executeUsd?: string;\n queryUsd?: string;\n [key: string]: unknown;\n}\n\nexport interface McpToolMeta {\n /** Declared method surface */\n surface?: McpToolSurface;\n\n /** Whether this method can be selected in query mode */\n queryEligible?: boolean;\n\n /** Declared latency class for runtime gating */\n latencyClass?: McpToolLatencyClass;\n\n /** Method-level pricing metadata */\n pricing?: McpToolPricingMeta;\n\n /** Derived discovery flag for execute eligibility */\n executeEligible?: boolean;\n\n /** Derived discovery field for explicit execute pricing visibility */\n executePriceUsd?: string;\n\n /** Context injection requirements handled by the Context runtime */\n contextRequirements?: string[];\n\n /**\n * Optional runtime pacing hints.\n * Tool contributors can publish these to reduce rate-limit failures.\n */\n rateLimit?: McpToolRateLimitHints;\n rateLimitHints?: McpToolRateLimitHints;\n\n /** Flat aliases accepted for convenience */\n maxRequestsPerMinute?: number;\n maxConcurrency?: number;\n cooldownMs?: number;\n supportsBulk?: boolean;\n recommendedBatchTools?: string[];\n notes?: string;\n\n [key: string]: unknown;\n}\n\nexport interface StructuredMethodGuidanceHints {\n /** Suggested call-order sequence extracted from method descriptions */\n callOrderHints?: string[];\n\n /** Parameter usage caveats extracted from method descriptions */\n parameterCaveats?: string[];\n\n /** Edge-case behavior notes extracted from method descriptions */\n edgeCaseNotes?: string[];\n}\n\nexport interface McpTool {\n /** Name of the MCP tool method */\n name: string;\n\n /** Description of what this method does */\n description: string;\n\n /**\n * JSON Schema for the input arguments this tool accepts.\n * Used by LLMs to generate correct arguments.\n */\n inputSchema?: Record<string, unknown>;\n\n /**\n * JSON Schema for the output this tool returns.\n * Used by LLMs to understand the response structure.\n */\n outputSchema?: Record<string, unknown>;\n\n /** MCP metadata extensions (context injection, rate-limit hints) */\n _meta?: McpToolMeta;\n\n /** Explicit execute eligibility in discovery responses */\n executeEligible?: boolean;\n\n /** Explicit execute price visibility in discovery responses */\n executePriceUsd?: string | null;\n\n /** Whether this method has normalized structured guidance hints */\n hasStructuredGuidance?: boolean;\n\n /** Optional structured guidance hints derived from the method description */\n structuredGuidance?: StructuredMethodGuidanceHints;\n}\n\n/**\n * Represents a tool available on the Context Protocol marketplace\n */\nexport interface Tool {\n /** Unique identifier for the tool (UUID) */\n id: string;\n\n /** Human-readable name of the tool */\n name: string;\n\n /** Description of what the tool does */\n description: string;\n\n /** Clickable example questions shown in the Context app */\n suggestedPrompts?: SuggestedPrompt[];\n\n /** Price per execution in USDC */\n price: string;\n\n /** Tool category (e.g., \"defi\", \"nft\") */\n category?: string;\n\n /** Whether the tool is verified by Context Protocol */\n isVerified?: boolean;\n\n /** Tool type - currently always \"mcp\" */\n kind?: string;\n\n /**\n * Available MCP tool methods\n * Use items from this array as `toolName` when executing\n */\n mcpTools?: McpTool[];\n\n // Trust metrics (Level 2 - Reputation Ledger)\n /** Total number of queries processed */\n totalQueries?: number;\n\n /** Success rate percentage (0-100) */\n successRate?: string;\n\n /** Uptime percentage (0-100) */\n uptimePercent?: string;\n\n /** Total USDC staked by the developer */\n totalStaked?: string;\n\n /** Whether the tool has \"Proven\" status (100+ queries, >95% success, >98% uptime) */\n isProven?: boolean;\n}\n\n/**\n * Response from the tools search endpoint\n */\nexport interface SearchResponse {\n /** Array of matching tools */\n tools: Tool[];\n\n /** Discovery mode used by the server */\n mode?: DiscoveryMode;\n\n /** The search query that was used */\n query: string;\n\n /** Total number of results */\n count: number;\n}\n\n/**\n * Options for searching tools\n */\nexport interface SearchOptions {\n /** Search query (semantic search) */\n query?: string;\n\n /** Maximum number of results (1-50, default 10) */\n limit?: number;\n\n /** Discovery mode with billing semantics */\n mode?: DiscoveryMode;\n\n /** Optional explicit method surface filter */\n surface?: McpToolSurface;\n\n /** Require methods marked query eligible */\n queryEligible?: boolean;\n\n /** Require explicit method execute pricing */\n requireExecutePricing?: boolean;\n\n /** Exclude methods by latency class */\n excludeLatencyClasses?: McpToolLatencyClass[];\n\n /** Convenience switch to exclude slow methods in query mode */\n excludeSlow?: boolean;\n\n /**\n * Restrict discovery to the caller's favorite tools.\n * - `true`: force favorites-only discovery for this request\n * - `false`: force unrestricted discovery for this request\n * - omitted: use the account-level default from Context settings\n */\n favoritesOnly?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Developer / tool management types\n// ---------------------------------------------------------------------------\n\n/**\n * Options for updating a tool listing via `client.developer.updateTool()`.\n * At least one field must be provided.\n */\nexport const ALLOWED_TOOL_CATEGORIES = [\n \"Crypto & DeFi\",\n \"Financial Markets\",\n \"Business & Sales\",\n \"Marketing & SEO\",\n \"Legal & Regulatory\",\n \"Real World\",\n \"Developer Tools\",\n \"Research & Academia\",\n \"Utility\",\n \"Other\",\n] as const;\n\nexport type ToolCategory = (typeof ALLOWED_TOOL_CATEGORIES)[number];\n\nexport interface UpdateToolOptions {\n /** New display name for the tool */\n name?: string;\n\n /** New marketplace description */\n description?: string;\n\n /** Validated example questions shown as clickable prompts in the Context app */\n suggestedPrompts?: SuggestedPrompt[];\n\n /** New category -- must be one of the predefined marketplace categories */\n category?: ToolCategory | null;\n}\n\n/**\n * Response from updating a tool listing.\n */\nexport interface UpdateToolResult {\n id: string;\n name: string;\n description: string;\n suggestedPrompts: SuggestedPrompt[];\n category: string | null;\n updatedAt: string;\n}\n\n/**\n * Options for executing a tool\n */\nexport interface ExecuteOptions {\n /** The UUID of the tool to execute (from search results) */\n toolId: string;\n\n /** The specific MCP tool name to call (from tool's mcpTools array) */\n toolName: string;\n\n /** Arguments to pass to the tool */\n args?: Record<string, unknown>;\n\n /**\n * Optional idempotency key (UUID recommended).\n * Reuse the same key when retrying the same logical request.\n */\n idempotencyKey?: string;\n\n /** Explicit execute mode label for request clarity */\n mode?: \"execute\";\n\n /** Optional execute session identifier */\n sessionId?: string;\n\n /** Optional per-session spend budget envelope (USD) */\n maxSpendUsd?: string;\n\n /** Request session closure after this execute call settles */\n closeSession?: boolean;\n}\n\nexport type ExecuteSessionStatus = \"open\" | \"closed\" | \"expired\";\n\nexport interface ExecuteSessionSpend {\n mode: \"execute\";\n sessionId: string | null;\n methodPrice: string;\n spent: string;\n remaining: string | null;\n maxSpend: string | null;\n\n /** Optional lifecycle fields when the API returns session state */\n status?: ExecuteSessionStatus;\n expiresAt?: string;\n closeRequested?: boolean;\n pendingAccruedCount?: number;\n pendingAccruedUsd?: string;\n}\n\n/**\n * Successful execution response from the API\n */\nexport interface ExecuteApiSuccessResponse {\n success: true;\n mode: \"execute\";\n\n /** The result data from the tool execution */\n result: unknown;\n\n /** Information about the executed tool */\n tool: {\n id: string;\n name: string;\n };\n\n /** Method-level execute pricing used for this call */\n method: {\n name: string;\n executePriceUsd: string;\n };\n\n /** Spend envelope visibility for execute sessions */\n session: ExecuteSessionSpend;\n\n /** Execution duration in milliseconds */\n durationMs: number;\n}\n\n/**\n * Error response from the API\n */\nexport interface ExecuteApiErrorResponse {\n /** Human-readable error message */\n error: string;\n\n /** Explicit mode label for clarity */\n mode?: \"execute\";\n\n /** Error code for programmatic handling */\n code?: ContextErrorCode;\n\n /** URL to help resolve the issue */\n helpUrl?: string;\n\n /** Optional spend envelope context when available */\n session?: ExecuteSessionSpend;\n}\n\n/**\n * Raw API response from the execute endpoint\n */\nexport type ExecuteApiResponse = ExecuteApiSuccessResponse | ExecuteApiErrorResponse;\n\nexport interface ExecuteSessionStartOptions {\n /** Maximum spend budget for the session (USD string) */\n maxSpendUsd: string;\n}\n\nexport interface ExecuteSessionApiSuccessResponse {\n success: true;\n mode: \"execute\";\n session: ExecuteSessionSpend;\n}\n\nexport type ExecuteSessionApiResponse =\n | ExecuteSessionApiSuccessResponse\n | ExecuteApiErrorResponse;\n\nexport interface ExecuteSessionResult {\n mode: \"execute\";\n session: ExecuteSessionSpend;\n}\n\n/**\n * The resolved result returned to the user after SDK processing\n */\nexport interface ExecutionResult<T = unknown> {\n mode: \"execute\";\n\n /** The data returned by the tool */\n result: T;\n\n /** Information about the executed tool */\n tool: {\n id: string;\n name: string;\n };\n\n /** Method-level execute pricing used for this call */\n method: {\n name: string;\n executePriceUsd: string;\n };\n\n /** Spend envelope visibility for execute calls */\n session: ExecuteSessionSpend;\n\n /** Execution duration in milliseconds */\n durationMs: number;\n}\n\n// ---------------------------------------------------------------------------\n// Query types (pay-per-response / agentic mode)\n// ---------------------------------------------------------------------------\n\n/**\n * Supported external orchestration depth hints for query execution.\n * The server decides the effective depth from the query; this is a soft hint.\n */\nexport type QueryDepth = \"fast\" | \"auto\" | \"deep\";\nexport type QueryOutcomeType = \"answer\" | \"capability_miss\";\nexport type QueryResponseShape =\n | \"answer\"\n | \"answer_with_evidence\"\n | \"evidence_only\";\nexport type QueryResponseEnvelopeViewType =\n | \"table\"\n | \"leaderboard\"\n | \"heatmap\"\n | \"timeseries\";\n\n/**\n * Supported high-level chart kinds produced by the librarian's\n * code interpreter. Each chart artifact is a structured spec + data pair\n * the SDK consumer can render with their preferred chart library\n * (the first-party UI uses Recharts via shadcn/ui).\n */\nexport type QueryChartType =\n | \"line\"\n | \"bar\"\n | \"area\"\n | \"scatter\"\n | \"composed\"\n | \"histogram\"\n | \"heatmap\"\n | \"candlestick\";\n\n/** Per-series rendering hint for a structured chart artifact. */\nexport type QueryChartSeriesType = \"line\" | \"bar\" | \"area\" | \"scatter\";\n\n/** Axis kind hint used by structured chart artifacts. */\nexport type QueryChartAxisType = \"time\" | \"category\" | \"number\";\n\n/** Axis value formatter hint used by structured chart artifacts. */\nexport type QueryChartValueFormat =\n | \"number\"\n | \"percent\"\n | \"currency\"\n | \"compact\";\n\n/** Allowed primitive cell value inside a chart data row. */\nexport type QueryChartDataValue = string | number | null;\n\n/** A single data row keyed by `xKey` plus each series key. */\nexport type QueryChartDataRow = Record<string, QueryChartDataValue>;\n\n/** Single series entry inside a structured chart spec. */\nexport interface QueryChartSeries {\n key: string;\n label?: string;\n type?: QueryChartSeriesType;\n errorKey?: string;\n yAxis?: \"left\" | \"right\";\n satisfies?: string;\n}\n\n/** Optional axis configuration for a structured chart spec. */\nexport interface QueryChartAxis {\n type?: QueryChartAxisType;\n label?: string;\n format?: QueryChartValueFormat;\n valueScale?: \"fraction\" | \"percent_points\";\n}\n\n/** Structured chart spec describing layout for a chart artifact. */\nexport interface QueryChartSpec {\n type: QueryChartType;\n xKey: string;\n series: QueryChartSeries[];\n expectedMeasures?: string[];\n xAxis?: QueryChartAxis;\n yAxis?: QueryChartAxis;\n yAxisRight?: QueryChartAxis;\n legend?: boolean;\n stacked?: boolean;\n brush?: boolean;\n referenceLines?: Array<{\n axis: \"x\" | \"y\";\n value: string | number;\n label?: string;\n }>;\n referenceAreas?: Array<{\n x1?: string | number;\n x2?: string | number;\n y1?: number;\n y2?: number;\n label?: string;\n }>;\n yKey?: string;\n valueKey?: string;\n ohlc?: {\n openKey: string;\n highKey: string;\n lowKey: string;\n closeKey: string;\n };\n}\n\n/**\n * Computed artifact emitted by the librarian's code interpreter.\n *\n * Charts are returned as a structured `{ spec, data }` pair so SDK consumers\n * can render them with any compatible charting library. The first-party web UI\n * renders these specs with Recharts.\n */\nexport type QueryComputedArtifact = {\n kind: \"chart\";\n spec: QueryChartSpec;\n data: QueryChartDataRow[];\n title?: string;\n};\n\nexport interface QueryToolCallFailureSample {\n /** Display name of the contributor tool whose call failed. */\n toolName: string;\n\n /** MCP method name that was invoked when the failure occurred. */\n methodName: string;\n\n /** Truncated failure reason captured from the runtime error. */\n reason: string;\n}\n\nexport interface QueryGroundingSummary {\n /** Marketplace methods registered in the iterative runtime, excluding control tools. */\n availableToolCount: number;\n\n /** Capped sample of method names available to the model. */\n availableMethodNamesSample: string[];\n\n /** Methods selected by retrieval/tool selection before runtime filtering. */\n selectedMethodCount: number;\n\n /** Capped list of selected methods that did not survive runtime filtering. */\n selectedButFilteredOut: string[];\n\n /** Grounded marketplace tool calls actually executed (successes only). */\n toolCallCount: number;\n\n /** Total marketplace method invocations attempted by the model (success + failure). */\n toolCallAttemptCount: number;\n\n /** Marketplace method invocations that completed without throwing. */\n toolCallSuccessCount: number;\n\n /** Marketplace method invocations that threw an error before returning data. */\n toolCallFailureCount: number;\n\n /** Capped sample of recent failed marketplace method invocations with reasons. */\n toolCallFailureSamples: QueryToolCallFailureSample[];\n\n /** True when the answer was grounded in at least one marketplace tool call. */\n grounded: boolean;\n}\n\nexport interface QueryCapabilityMissPayload {\n message: string;\n missingCapabilities: string[];\n suggestedRewrites: string[];\n originalQuery: string;\n}\n\nexport interface QueryAssumptionMetadata {\n mode: \"auto\";\n optionId: string;\n label: string;\n reason: string;\n}\n\nexport type QueryAttemptForkReason =\n | \"manual_fork\"\n | \"bounded_rediscovery\"\n | \"resume_replay\"\n | \"patch_retry\"\n | \"unknown\";\n\n/**\n * Options for the agentic query endpoint (pay-per-response).\n *\n * Unlike `execute()` which calls a single tool once, `query()` sends a\n * natural-language question and lets the server handle the live librarian\n * pipeline (`discover -> select -> iterative execute -> synthesize ->\n * settle`).\n * One flat fee covers up to 100 MCP skill calls per tool.\n */\nexport interface QueryOptions {\n /** The natural-language question to answer */\n query: string;\n\n /**\n * Optional tool IDs to use. When omitted the server discovers tools\n * automatically (Auto Mode). When provided, only these tools are used\n * (Manual Mode).\n */\n tools?: string[];\n\n /**\n * Restrict auto-discovery to the caller's favorite tools.\n * Ignored when `tools` is provided because manual tool selection wins.\n * - `true`: force favorites-only discovery for this request\n * - `false`: force unrestricted discovery for this request\n * - omitted: use the account-level default from Context settings\n */\n favoritesOnly?: boolean;\n\n /**\n * Resume a prior durable query attempt from its latest checkpoint.\n * Cannot be combined with `tools` or `forkFrom`.\n */\n resumeFrom?: QueryAttemptReference;\n\n /**\n * Fork a new durable query attempt from a previous attempt.\n * Optional `reason` keeps the server's non-breaking lineage metadata honest.\n * Cannot be combined with `tools` or `resumeFrom`.\n */\n forkFrom?: QueryForkReference;\n\n /**\n * Optional answer model ID for final synthesis.\n * Supported IDs are published by the Context API. Ignored when\n * `responseShape` is `evidence_only` because synthesis is skipped.\n */\n answerModelId?: string;\n\n /**\n * Structured response mode for query answers. The runtime always produces a\n * grounded result (raw data + computed artifacts + provenance); responseShape\n * controls whether a prose synthesis layer is added on top.\n * - `answer_with_evidence`: prose answer plus the structured grounding (chat parity)\n * - `evidence_only`: structured grounding only, no prose — the agent-harness\n * shape. Returns raw `data` + `computedArtifacts` + `grounding`/`evidence`\n * by default so your own agent can reason over the result.\n * - `answer`: legacy prose-only shape, kept for backward compatibility.\n */\n responseShape?: QueryResponseShape;\n\n /**\n * Include raw execution data inline in the query response.\n * Defaults to true for responseShape `evidence_only` (its primary payload is\n * the raw fetched data); false otherwise. Set explicitly to override — e.g.\n * `false` on evidence_only to rely on `dataUrl`/`canonicalDataRef` instead.\n */\n includeData?: boolean;\n\n /**\n * Persist execution data to Vercel Blob and return a download URL.\n * Useful for large payload workflows where inline JSON is not ideal.\n */\n includeDataUrl?: boolean;\n\n /**\n * Include machine-readable developer trace output for this query response.\n * When enabled, the server may return summary counters plus diagnostics\n * for tool selection and iterative execution behavior.\n */\n includeDeveloperTrace?: boolean;\n\n /**\n * Optional idempotency key (UUID recommended).\n * Reuse the same key when retrying the same logical request.\n */\n idempotencyKey?: string;\n}\n\n/**\n * Tool reference attached to developer trace timeline steps.\n */\nexport interface QueryDeveloperTraceToolRef {\n id?: string;\n name?: string;\n method?: string;\n [key: string]: unknown;\n}\n\n/**\n * Loop metadata attached to developer trace timeline steps.\n */\nexport interface QueryDeveloperTraceLoopInfo {\n name?: string;\n iteration?: number;\n maxIterations?: number;\n [key: string]: unknown;\n}\n\n/**\n * Tool selection metadata attached to discovery diagnostics.\n */\nexport interface QueryDeveloperTraceToolSelection {\n toolId: string;\n toolName: string;\n selectedMethodCount: number;\n selectedMethods: string[];\n omittedSelectedMethodCount: number;\n priceUsd?: string;\n}\n\n/**\n * Execution-contract details handed to the iterative runtime.\n */\nexport interface QueryPlanningTraceDiagnostic {\n plannerQuery: string;\n scoutEvidenceAttached: boolean;\n scoutEvidencePromptBlock: string | null;\n allowedModules: string[];\n}\n\n/**\n * Rediscovery/fallback diagnostic details.\n */\nexport interface QueryRediscoveryTraceDiagnostic {\n considered: boolean;\n executed: boolean;\n skipReason: string | null;\n missingCapability: string | null;\n rediscoveryQuery: string | null;\n capabilityLooksLikeSearchNeed: boolean;\n allowSearchFallbackOnElapsedCap: boolean;\n searchFallbackUsed: boolean;\n preRediscoveryBudgetReasonCode: string | null;\n candidateSearchResults: QueryDeveloperTraceToolSelection[];\n selectedAlternatives: QueryDeveloperTraceToolSelection[];\n mergedTools: QueryDeveloperTraceToolSelection[];\n usingPaidFallback: boolean;\n branchPlan: QueryPlanningTraceDiagnostic | null;\n}\n\nexport interface QueryCompletenessRepairEvent {\n attempt: number;\n outcome:\n | \"attempted\"\n | \"skipped_by_guardrail\"\n | \"skipped_no_retry_budget\"\n | \"skipped_needs_different_tools\"\n | \"skipped_no_retry_path\"\n | \"patch_failed\"\n | \"replan_failed\"\n | \"patched\"\n | \"replanned\";\n semanticRetryCount: number;\n maxSemanticRetries: number;\n strategy: \"patch\" | \"replan\" | null;\n summary: string | null;\n failReason: string | null;\n requestedReplan: boolean;\n hadSyntaxFix: boolean;\n editCount: number | null;\n skipReason: string | null;\n boundedAnswerReason:\n | \"retry_guardrail_same_endpoint_fanout\"\n | \"retry_guardrail_upstream_abort\"\n | null;\n blockingDiagnostics: Array<{\n code: string;\n severity: string;\n message: string;\n }>;\n}\n\n/**\n * Rich developer-trace diagnostics for managed query-runtime internals.\n */\nexport interface QueryDeveloperTraceDiagnostics {\n selection: {\n selectedPolicy: string;\n debugScoutDeepMode: string | null;\n plannerReasoningStage: string;\n scoutEnabled: boolean;\n oneShotBias: boolean;\n candidateMethodCount: number;\n scoutProbeStatus: string;\n scoutProbeAdequacy: string;\n scoutProbeConfidence: number;\n scoutMetadataConfidence: number;\n scoutProbeQuerySafeCandidateCount: number;\n scoutProbeRankedMethodCount: number;\n scoutProbeAmbiguityPoolCount: number;\n scoutProbeShortlistedMethodCount: number;\n scoutProbeMissingCapability: string | null;\n scoutPrePlanProbeCalls: number;\n scoutPrePlanProbeBudgetReasonCode: string | null;\n scoutChangedInitialPlan: boolean;\n scoutChangedPlannerReasoningStage: boolean;\n scoutInitialSelectedPolicy: string;\n scoutInitialPlannerReasoningStage: string;\n scoutInitialReasonCode: string;\n scoutFinalReasonCode: string;\n scoutEvidenceAttachedToPlanning: boolean;\n scoutLlmSelectionUsed: boolean;\n scoutLlmSelectionFallback: boolean;\n scoutLlmSelectionLatencyMs: number | null;\n selectedTools: QueryDeveloperTraceToolSelection[];\n };\n executionContract?: QueryPlanningTraceDiagnostic;\n cost?: {\n planningCostUsd: number;\n initialExecutionCostUsd: number;\n rediscoveryAdditionalCostUsd: number;\n synthesisCostUsd: number;\n totalModelCostUsd: number;\n toolCostUsd: number;\n totalChargedUsd: number;\n };\n verification: {\n evaluations: unknown[];\n repairEvents: QueryCompletenessRepairEvent[];\n triggerNeedsDifferentTools: boolean;\n triggerMissingCapability: string | null;\n };\n execution?: {\n reasoningEnabled: boolean;\n receivedReasoning: boolean;\n reasoningChars: number;\n scoutEvidenceInjected: boolean;\n stepBudget: number;\n completedStepCount: number;\n toolCallCount?: number;\n toolRegistry?: Omit<QueryGroundingSummary, \"toolCallCount\" | \"grounded\">;\n };\n contributorSearches?: ContributorSearchTraceRecord[];\n [key: string]: unknown;\n}\n\n/**\n * A single developer-trace timeline step.\n */\nexport interface QueryDeveloperTraceStep {\n stepType?: string;\n event?: string;\n status?: string;\n message?: string;\n timestampMs?: number;\n tool?: QueryDeveloperTraceToolRef;\n attempt?: number;\n loop?: QueryDeveloperTraceLoopInfo;\n metadata?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n/**\n * Aggregate counters that summarize developer-trace behavior.\n */\nexport interface QueryDeveloperTraceSummary {\n toolCalls?: number;\n retryCount?: number;\n selfHealCount?: number;\n fallbackCount?: number;\n failureCount?: number;\n recoveryCount?: number;\n completionChecks?: number;\n loopCount?: number;\n [key: string]: unknown;\n}\n\n/**\n * Full tool call record (untruncated) for debugging.\n */\nexport interface QueryDeveloperTraceToolCall {\n toolId?: string;\n toolName: string;\n args?: unknown;\n result: unknown;\n}\n\n/**\n * MCP method schema exposed in the developer trace.\n */\nexport interface QueryDeveloperTraceToolSchema {\n serverName: string;\n toolName: string;\n description: string;\n inputSchema?: Record<string, unknown>;\n outputSchema?: Record<string, unknown>;\n}\n\n/**\n * Developer Mode trace payload returned per query response (opt-in).\n */\nexport interface QueryDeveloperTrace {\n summary?: QueryDeveloperTraceSummary;\n timeline?: QueryDeveloperTraceStep[];\n requestId?: string;\n query?: string;\n source?: string;\n diagnostics?: QueryDeveloperTraceDiagnostics;\n initialCode?: string;\n finalCode?: string;\n executionTrace?: unknown[];\n executionProgram?: unknown;\n attemptCount?: number;\n executionSuccess?: boolean;\n executionResult?: unknown;\n toolCallHistory?: QueryDeveloperTraceToolCall[];\n toolSchemas?: QueryDeveloperTraceToolSchema[];\n [key: string]: unknown;\n}\n\n/**\n * Information about a tool that was used during a query response\n */\nexport interface QueryToolUsage {\n /** Tool ID */\n id: string;\n\n /** Tool name */\n name: string;\n\n /** Number of MCP skill calls made for this tool */\n skillCalls: number;\n}\n\n/**\n * Cost breakdown for a query response.\n * All values are strings representing USD amounts.\n */\nexport interface QueryCost {\n /** AI model inference cost */\n modelCostUsd: string;\n\n /** Sum of all tool fees */\n toolCostUsd: string;\n\n /** Total cost (model + tools) */\n totalCostUsd: string;\n}\n\n/**\n * High-level orchestration outcome metrics returned by the query API.\n */\nexport interface QueryOrchestrationMetrics {\n parityStage: string;\n orchestrationMode: string;\n /** Whether the first plan path succeeded without fallback. */\n firstPassSuccess: boolean;\n /** Whether execution signaled a missing capability on first pass. */\n capabilityMissSignaled: boolean;\n /** Whether bounded rediscovery/fallback executed. */\n rediscoveryExecuted: boolean;\n}\n\nexport interface QueryAttemptReference {\n sessionId: string;\n attemptId: string;\n}\n\n/** Public fork handle for creating a new attempt from a prior Query session. */\nexport interface QueryForkReference extends QueryAttemptReference {\n reason?: QueryAttemptForkReason;\n}\n\n/**\n * Public continuation state returned by headless Query responses.\n * Internal selected-tool lineage remains durable server state but is not\n * exposed as chat-style payloads.\n */\nexport interface QuerySessionState {\n sessionId: string;\n attemptId: string;\n parentAttemptId: string | null;\n rootAttemptId: string;\n mode: \"initial\" | \"resume\" | \"fork\";\n origin: \"initial_request\" | \"resume\" | \"fork\";\n status: \"active\" | \"completed\" | \"failed\" | \"aborted\";\n checkpoint: {\n currentStage: string | null;\n latestCheckpointArtifactId: string | null;\n canonicalDatasetId: string | null;\n executionProgramCurrentRevisionId: string | null;\n };\n}\n\nexport interface QueryResponseEnvelopeFact {\n id: string;\n label: string;\n path: string | null;\n relevanceScore: number | null;\n value: unknown;\n}\n\nexport interface QueryResponseEnvelopeSourceRef {\n id: string;\n provider: string | null;\n dataset: string | null;\n observedAt: string | null;\n publishedAt: string | null;\n artifactRef: string | null;\n url: string | null;\n note: string | null;\n}\n\nexport type QueryResponseEnvelopeTone =\n | \"positive\"\n | \"negative\"\n | \"neutral\"\n | \"caution\";\n\nexport type QueryControllerStopReason =\n | \"complete_answer\"\n | \"bounded_runtime_budget\"\n | \"bounded_same_endpoint_guardrail\"\n | \"bounded_upstream_abort_guardrail\"\n | \"capability_miss\";\n\nexport type QueryControllerIssueClass =\n | \"missing_evidence\"\n | \"missing_capability\"\n | \"stale_data\"\n | \"wrong_tool_path\";\n\nexport type QueryControllerAction =\n | \"inspect_current_grounding\"\n | \"patch_current_program\"\n | \"bounded_rediscovery\"\n | \"return_capability_miss\"\n | \"return_bounded_answer\"\n | \"return_complete_answer\";\n\nexport interface QueryResponseEnvelopeMarketAggregateFlow {\n netFlowUsd: number | null;\n grossInflowUsd: number | null;\n grossOutflowUsd: number | null;\n nativeNetFlow: number | null;\n nativeUnit: string | null;\n direction: \"inflow\" | \"outflow\" | \"flat\" | \"mixed\";\n}\n\nexport interface QueryResponseEnvelopeMarketVenueBreakdown {\n venue: string;\n asset: string | null;\n netFlowUsd: number | null;\n grossInflowUsd: number | null;\n grossOutflowUsd: number | null;\n nativeNetFlow: number | null;\n nativeUnit: string | null;\n shareOfTotal: number | null;\n rank: number | null;\n}\n\nexport interface QueryResponseEnvelopeCatalystRef {\n source: string;\n publishedAt: string | null;\n claim: string | null;\n relationToFlow: string | null;\n url: string | null;\n}\n\nexport interface QueryResponseEnvelopeDerivativesContext {\n openInterestDirection: string | null;\n openInterestChangePct: number | null;\n liquidationBias: string | null;\n venues: string[];\n relationshipToSpotFlows: string | null;\n}\n\nexport interface QueryResponseEnvelopeMarketIntelligence {\n asset: string | null;\n assets: string[] | null;\n timeWindow: string | null;\n asOf: string | null;\n aggregateFlow: QueryResponseEnvelopeMarketAggregateFlow | null;\n venueBreakdown: QueryResponseEnvelopeMarketVenueBreakdown[];\n catalystRefs: QueryResponseEnvelopeCatalystRef[];\n derivativesContext: QueryResponseEnvelopeDerivativesContext | null;\n}\n\nexport interface QueryResponseEnvelopeViewMetric {\n label: string;\n value: string;\n tone?: QueryResponseEnvelopeTone;\n}\n\nexport interface QueryResponseEnvelopeViewRow {\n key: string;\n cells: string[];\n tone?: QueryResponseEnvelopeTone;\n sourceRefIds?: string[];\n}\n\nexport interface QueryResponseEnvelope {\n responseShape: Exclude<QueryResponseShape, \"answer\">;\n response: string;\n summary: string;\n outcome: {\n label: string;\n tone: QueryResponseEnvelopeTone;\n stopReason: QueryControllerStopReason;\n issueClass: QueryControllerIssueClass | null;\n };\n controller: {\n scope: \"wedge\" | \"standard\";\n nextAction: QueryControllerAction;\n actionsTaken: QueryControllerAction[];\n patchFirstProgramPreserved: boolean;\n executionProgramRevisionId: string | null;\n hardBudgetApplied: boolean;\n } | null;\n evidence: {\n facts: QueryResponseEnvelopeFact[];\n sourceRefs: QueryResponseEnvelopeSourceRef[];\n assumptions: string[];\n knownUnknowns: string[];\n retrievalPlanReasonCodes: string[];\n marketIntelligence?: QueryResponseEnvelopeMarketIntelligence | null;\n };\n artifacts: {\n dataUrl: string | null;\n canonicalDataRef: {\n datasetId: string;\n hash: string;\n bytes: number;\n publicDataUrl: string | null;\n } | null;\n stageArtifactKinds: string[];\n };\n view: {\n type: QueryResponseEnvelopeViewType;\n label: string;\n title?: string | null;\n metrics?: QueryResponseEnvelopeViewMetric[];\n columns?: string[];\n rows?: QueryResponseEnvelopeViewRow[];\n } | null;\n freshness: {\n asOf: string | null;\n sourceTimestamps: string[];\n note: string;\n };\n confidence: {\n level: \"high\" | \"medium\" | \"low\";\n reason: string;\n verifiedFactCount: number;\n inferredFactCount: number;\n gapCount: number;\n gapSignals: Array<{\n code: string;\n severity: string;\n detail: string;\n }>;\n };\n usage: {\n durationMs: number;\n cost: QueryCost;\n toolsUsed: QueryToolUsage[];\n outcomeType: QueryOutcomeType;\n orchestrationMetrics?: QueryOrchestrationMetrics;\n };\n}\n\nexport interface QueryBaseResult {\n /** The answer text or machine-friendly summary returned for this query. */\n response: string;\n\n /** Tools that were used to answer the query */\n toolsUsed: QueryToolUsage[];\n\n /** Cost breakdown */\n cost: QueryCost;\n\n /** Total duration in milliseconds */\n durationMs: number;\n\n /**\n * Raw execution data from tools — the actual MCP/tool outputs.\n * Returned by default for responseShape `evidence_only` (the agent-harness\n * shape, whose primary payload is the raw data). For other shapes it is\n * returned only when `includeData` is true.\n */\n data?: unknown;\n\n /** Optional blob URL for persisted execution data (when includeDataUrl=true) */\n dataUrl?: string;\n\n /** Optional derived artifacts emitted by code_interpreter in answer mode. */\n computedArtifacts?: QueryComputedArtifact[];\n\n /** Public grounding summary for marketplace tool execution. */\n grounding?: QueryGroundingSummary;\n\n /** Optional machine-readable Developer Mode trace payload */\n developerTrace?: QueryDeveloperTrace;\n\n /** Optional orchestration outcome metrics for benchmarking and rollout analysis */\n orchestrationMetrics?: QueryOrchestrationMetrics;\n\n /** Typed public stop reason for the final outcome. */\n stopReason?: QueryControllerStopReason;\n\n /** Typed issue class exposed by the bounded controller contract. */\n issueClass?: QueryControllerIssueClass | null;\n\n /** Ordered public controller actions taken before the final outcome. */\n actionsTaken?: QueryControllerAction[];\n\n /** Optional controller summary for bounded wedge-style answers. */\n controller?: QueryResponseEnvelope[\"controller\"];\n\n /**\n * Optional public durable continuation handles for resume/fork flows.\n * Query exposes handle-based continuation, not chat-style continuation payloads.\n */\n querySession?: QuerySessionState;\n}\n\n/**\n * The resolved result of a pay-per-response query\n */\nexport type QueryResult =\n | (QueryBaseResult &\n Partial<QueryResponseEnvelope> & {\n outcomeType: \"answer\";\n assumptionMade?: QueryAssumptionMetadata;\n })\n | (QueryBaseResult & {\n outcomeType: \"capability_miss\";\n capabilityMiss: QueryCapabilityMissPayload;\n });\n\n/**\n * Successful response from the /api/v1/query endpoint\n */\nexport type QueryApiSuccessResponse = { success: true } & QueryResult;\n\n/**\n * Raw API response from the query endpoint\n */\nexport type QueryApiResponse = QueryApiSuccessResponse | ExecuteApiErrorResponse;\n\n// ---------------------------------------------------------------------------\n// Query stream event types\n// ---------------------------------------------------------------------------\n\n/** Emitted when a tool starts or changes execution status */\nexport interface QueryStreamToolStatusEvent {\n type: \"tool-status\";\n tool: { id: string; name: string };\n status: string;\n}\n\n/** Emitted for each chunk of the AI response text */\nexport interface QueryStreamTextDeltaEvent {\n type: \"text-delta\";\n delta: string;\n}\n\n/** Emitted when the server streams developer trace updates/chunks */\nexport interface QueryStreamDeveloperTraceEvent {\n type: \"developer-trace\";\n trace: QueryDeveloperTrace;\n}\n\n/** Emitted when the full response is complete */\nexport interface QueryStreamDoneEvent {\n type: \"done\";\n result: QueryResult;\n}\n\n/** Emitted when the server reports a recoverable or terminal query error */\nexport interface QueryStreamErrorEvent {\n type: \"error\";\n error: string;\n code?: ContextErrorCode | string;\n scope?: string;\n reasonCode?: string;\n outcomeType?: Exclude<QueryOutcomeType, \"answer\">;\n capabilityMiss?: QueryCapabilityMissPayload;\n querySession?: QuerySessionState;\n}\n\n/**\n * Union of all events emitted during a streaming query\n */\nexport type QueryStreamEvent =\n | QueryStreamToolStatusEvent\n | QueryStreamTextDeltaEvent\n | QueryStreamDeveloperTraceEvent\n | QueryStreamDoneEvent\n | QueryStreamErrorEvent;\n\n// ---------------------------------------------------------------------------\n// Error types\n// ---------------------------------------------------------------------------\n\n/**\n * Specific error codes returned by the Context Protocol API\n */\nexport type ContextErrorCode =\n | \"unauthorized\"\n | \"no_wallet\"\n | \"insufficient_allowance\"\n | \"payment_failed\"\n | \"execution_failed\"\n | \"query_failed\"\n | \"invalid_tool_method\"\n | \"method_not_execute_eligible\"\n | \"invalid_max_spend\"\n | \"session_not_found\"\n | \"session_forbidden\"\n | \"session_closed\"\n | \"session_expired\"\n | \"max_spend_mismatch\"\n | \"session_budget_exceeded\";\n\n/**\n * Error thrown by the Context Protocol client\n */\nexport class ContextError extends Error {\n constructor(\n message: string,\n public readonly code?: ContextErrorCode | string,\n public readonly statusCode?: number,\n public readonly helpUrl?: string\n ) {\n super(message);\n this.name = \"ContextError\";\n Object.setPrototypeOf(this, ContextError.prototype);\n }\n}\n","import type { UpdateToolOptions, UpdateToolResult } from \"../types.js\";\nimport { ALLOWED_TOOL_CATEGORIES, ContextError } from \"../types.js\";\nimport type { ContextClient } from \"../client.js\";\n\n/**\n * Developer resource for managing tool listings on the Context Protocol marketplace.\n *\n * Scoped to contributor/developer concerns (listing management), separate from\n * the consumer-facing `tools.execute()` and `query.run()`.\n */\nexport class Developer {\n constructor(private client: ContextClient) {}\n\n /**\n * Update a tool listing's metadata (name, description, category).\n *\n * Requires an API key belonging to the tool's owner.\n *\n * @param toolId - The UUID of the tool to update\n * @param updates - Fields to update (at least one required)\n * @returns The updated tool metadata\n *\n * @throws {ContextError} If authentication fails or the caller does not own the tool\n *\n * @example\n * ```typescript\n * const updated = await client.developer.updateTool(\"tool-uuid\", {\n * description: \"Updated description with better showcase prompts\",\n * category: \"crypto\",\n * });\n * console.log(updated.updatedAt);\n * ```\n */\n async updateTool(\n toolId: string,\n updates: UpdateToolOptions\n ): Promise<UpdateToolResult> {\n if (!toolId) {\n throw new ContextError(\"toolId is required\");\n }\n\n if (\n updates.name === undefined &&\n updates.description === undefined &&\n updates.suggestedPrompts === undefined &&\n updates.category === undefined\n ) {\n throw new ContextError(\n \"At least one field required: name, description, suggestedPrompts, or category\"\n );\n }\n\n if (\n updates.category !== undefined &&\n updates.category !== null &&\n !ALLOWED_TOOL_CATEGORIES.includes(updates.category)\n ) {\n throw new ContextError(\n `category must be one of: ${ALLOWED_TOOL_CATEGORIES.join(\", \")}`\n );\n }\n\n const encodedToolId = encodeURIComponent(toolId);\n\n return this.client._fetch<UpdateToolResult>(\n `/api/v1/tools/${encodedToolId}`,\n {\n method: \"PATCH\",\n body: JSON.stringify(updates),\n },\n { retry: false }\n );\n }\n}\n","import type { SearchOptions, SearchResponse, Tool } from \"../types.js\";\nimport type { ContextClient } from \"../client.js\";\n\n/**\n * Discovery resource for searching and finding tools on the Context Protocol marketplace\n */\nexport class Discovery {\n constructor(private client: ContextClient) {}\n\n /**\n * Fetch a single marketplace tool by its unique ID.\n */\n async get(toolId: string): Promise<Tool> {\n return this.client._fetch<Tool>(\n `/api/v1/tools/${encodeURIComponent(toolId)}`\n );\n }\n\n /**\n * Search for tools matching a query string.\n *\n * Backward-compatible signatures:\n * - `search(\"gas prices\", 10)`\n * - `search({ query: \"gas prices\", limit: 10, mode: \"execute\" })`\n */\n async search(query: string, limit?: number): Promise<Tool[]>;\n async search(options: SearchOptions): Promise<Tool[]>;\n async search(\n queryOrOptions: string | SearchOptions,\n limit?: number\n ): Promise<Tool[]> {\n const options: SearchOptions =\n typeof queryOrOptions === \"string\"\n ? { query: queryOrOptions, limit }\n : queryOrOptions;\n\n const params = new URLSearchParams();\n const query = options.query ?? \"\";\n\n if (query) {\n params.set(\"q\", query);\n }\n\n if (options.limit !== undefined) {\n params.set(\"limit\", String(options.limit));\n }\n\n if (options.mode) {\n params.set(\"mode\", options.mode);\n }\n\n if (options.surface) {\n params.set(\"surface\", options.surface);\n }\n\n if (options.queryEligible !== undefined) {\n params.set(\"queryEligible\", String(options.queryEligible));\n }\n\n if (options.requireExecutePricing !== undefined) {\n params.set(\n \"requireExecutePricing\",\n String(options.requireExecutePricing)\n );\n }\n\n if (\n options.excludeLatencyClasses &&\n options.excludeLatencyClasses.length > 0\n ) {\n params.set(\"excludeLatency\", options.excludeLatencyClasses.join(\",\"));\n }\n\n if (options.excludeSlow !== undefined) {\n params.set(\"excludeSlow\", String(options.excludeSlow));\n }\n\n if (options.favoritesOnly !== undefined) {\n params.set(\"favorites_only\", String(options.favoritesOnly));\n }\n\n const queryString = params.toString();\n const endpoint = `/api/v1/tools/search${queryString ? `?${queryString}` : \"\"}`;\n\n const response = await this.client._fetch<SearchResponse>(endpoint);\n\n return response.tools;\n }\n\n /**\n * Get featured/popular tools (empty query search)\n *\n * @param limit - Maximum number of results (1-50, default 10)\n * @returns Array of featured tools\n *\n * @example\n * ```typescript\n * const featured = await client.discovery.getFeatured(5);\n * ```\n */\n async getFeatured(\n limit?: number,\n options?: Omit<SearchOptions, \"query\" | \"limit\">\n ): Promise<Tool[]> {\n return this.search({\n ...(options ?? {}),\n query: \"\",\n ...(limit !== undefined ? { limit } : {}),\n });\n }\n}\n","import type {\n ExecuteOptions,\n ExecuteApiResponse,\n ExecuteSessionApiResponse,\n ExecuteSessionResult,\n ExecuteSessionStartOptions,\n ExecutionResult,\n} from \"../types.js\";\nimport { ContextError } from \"../types.js\";\nimport type { ContextClient } from \"../client.js\";\n\n/**\n * Tools resource for executing tools on the Context Protocol marketplace\n */\nexport class Tools {\n constructor(private client: ContextClient) {}\n\n /**\n * Execute a tool with the provided arguments\n *\n * @param options - Execution options\n * @param options.toolId - The UUID of the tool (from search results)\n * @param options.toolName - The specific MCP tool method to call (from tool's mcpTools array)\n * @param options.args - Arguments to pass to the tool\n * @returns The execution result with the tool's output data\n *\n * @throws {ContextError} With code `no_wallet` if wallet not set up\n * @throws {ContextError} With code `insufficient_allowance` if spending cap not set\n * @throws {ContextError} With code `payment_failed` if payment settlement fails\n * @throws {ContextError} With code `execution_failed` if tool execution fails\n *\n * @example\n * ```typescript\n * // First, search for a tool\n * const tools = await client.discovery.search(\"gas prices\");\n * const tool = tools[0];\n *\n * // Execute a specific method from the tool's mcpTools\n * const result = await client.tools.execute({\n * toolId: tool.id,\n * toolName: tool.mcpTools[0].name, // e.g., \"get_gas_prices\"\n * args: { chainId: 1 }\n * });\n *\n * console.log(result.result); // The tool's output\n * console.log(result.durationMs); // Execution time\n * ```\n */\n async execute<T = unknown>(options: ExecuteOptions): Promise<ExecutionResult<T>> {\n const {\n toolId,\n toolName,\n args,\n idempotencyKey,\n mode,\n sessionId,\n maxSpendUsd,\n closeSession,\n } = options;\n const headers = idempotencyKey\n ? { \"Idempotency-Key\": idempotencyKey }\n : undefined;\n\n const response = await this.client._fetch<ExecuteApiResponse>(\n \"/api/v1/tools/execute\",\n {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n toolId,\n toolName,\n args,\n mode: mode ?? \"execute\",\n sessionId,\n maxSpendUsd,\n closeSession,\n }),\n }\n );\n\n // Handle error response\n if (\"error\" in response) {\n throw new ContextError(\n response.error,\n response.code,\n undefined, // Don't hardcode - this was a 200 OK with error body\n response.helpUrl\n );\n }\n\n // Handle success response\n if (response.success) {\n return {\n mode: response.mode,\n result: response.result as T,\n tool: response.tool,\n method: response.method,\n session: response.session,\n durationMs: response.durationMs,\n };\n }\n\n // Fallback - shouldn't reach here with valid API responses\n throw new ContextError(\"Unexpected response format from API\");\n }\n\n /**\n * Start an execute session with a max spend budget.\n */\n async startSession(\n options: ExecuteSessionStartOptions\n ): Promise<ExecuteSessionResult> {\n const response = await this.client._fetch<ExecuteSessionApiResponse>(\n \"/api/v1/tools/execute/sessions\",\n {\n method: \"POST\",\n body: JSON.stringify({\n mode: \"execute\",\n maxSpendUsd: options.maxSpendUsd,\n }),\n }\n );\n\n return this.resolveSessionLifecycleResponse(response);\n }\n\n /**\n * Fetch current execute session status by ID.\n */\n async getSession(sessionId: string): Promise<ExecuteSessionResult> {\n if (!sessionId) {\n throw new ContextError(\"sessionId is required\");\n }\n\n const encodedSessionId = encodeURIComponent(sessionId);\n const response = await this.client._fetch<ExecuteSessionApiResponse>(\n `/api/v1/tools/execute/sessions/${encodedSessionId}`\n );\n\n return this.resolveSessionLifecycleResponse(response);\n }\n\n /**\n * Close an execute session by ID.\n */\n async closeSession(sessionId: string): Promise<ExecuteSessionResult> {\n if (!sessionId) {\n throw new ContextError(\"sessionId is required\");\n }\n\n const encodedSessionId = encodeURIComponent(sessionId);\n const response = await this.client._fetch<ExecuteSessionApiResponse>(\n `/api/v1/tools/execute/sessions/${encodedSessionId}/close`,\n {\n method: \"POST\",\n body: JSON.stringify({ mode: \"execute\" }),\n }\n );\n\n return this.resolveSessionLifecycleResponse(response);\n }\n\n private resolveSessionLifecycleResponse(\n response: ExecuteSessionApiResponse\n ): ExecuteSessionResult {\n if (\"error\" in response) {\n throw new ContextError(\n response.error,\n response.code,\n undefined,\n response.helpUrl\n );\n }\n\n if (response.success) {\n return {\n mode: response.mode,\n session: response.session,\n };\n }\n\n throw new ContextError(\"Unexpected response format from API\");\n }\n}\n","import type {\n QueryOptions,\n QueryDeveloperTrace,\n QueryResult,\n QueryStreamEvent,\n} from \"../types.js\";\nimport { ContextError } from \"../types.js\";\nimport type { ContextClient } from \"../client.js\";\n\n/**\n * Query resource for pay-per-response agentic queries.\n *\n * Unlike `tools.execute()` which calls a single tool once (pay-per-request),\n * the Query resource sends a natural-language question and lets the server\n * handle the live librarian pipeline (`discover -> select -> metadata scout ->\n * iterative execute -> synthesize -> settle`) plus AI\n * synthesis — all for one flat fee.\n *\n * This is the \"prepared meal\" vs \"raw ingredients\" distinction:\n * - `tools.execute()` = raw data, full control, predictable cost\n * - `query.run()` / `query.stream()` = curated intelligence, one payment\n */\nexport class Query {\n constructor(private client: ContextClient) {}\n\n private normalizeResult(result: QueryResult): QueryResult {\n const candidate = result as QueryResult & { outcomeType?: string };\n if (\n candidate.outcomeType === \"capability_miss\" &&\n \"capabilityMiss\" in candidate &&\n candidate.capabilityMiss\n ) {\n return candidate;\n }\n return {\n ...candidate,\n outcomeType: \"answer\",\n };\n }\n\n private buildSyntheticTraceFromRunResult(params: {\n toolsUsed: Array<{ id: string; name: string; skillCalls: number }>;\n durationMs: number;\n }): QueryDeveloperTrace {\n const timeline = params.toolsUsed.map((tool, index) => ({\n stepType: \"tool-call\",\n event: \"tool-call\",\n status: \"success\",\n timestampMs: index,\n tool: {\n id: tool.id,\n name: tool.name,\n },\n metadata: {\n skillCalls: tool.skillCalls,\n synthetic: true,\n },\n }));\n\n const toolCalls = params.toolsUsed.reduce(\n (sum, tool) => sum + Math.max(tool.skillCalls, 0),\n 0\n );\n\n return {\n summary: {\n toolCalls,\n retryCount: 0,\n selfHealCount: 0,\n fallbackCount: 0,\n failureCount: 0,\n recoveryCount: 0,\n completionChecks: 0,\n loopCount: 0,\n },\n timeline,\n source: \"sdk-fallback\",\n synthetic: true,\n reason: \"backend_trace_missing\",\n durationMs: params.durationMs,\n };\n }\n\n private buildSyntheticTraceFromStreamStatus(params: {\n statusTimeline: Array<{\n status: string;\n tool: { id: string; name: string };\n }>;\n toolsUsed: Array<{ id: string; name: string; skillCalls: number }>;\n durationMs: number;\n }): QueryDeveloperTrace {\n const timeline = params.statusTimeline.map((entry, index) => ({\n stepType: \"tool-status\",\n event: \"tool-status\",\n status: entry.status,\n timestampMs: index,\n tool:\n entry.tool.name || entry.tool.id\n ? {\n id: entry.tool.id || undefined,\n name: entry.tool.name || undefined,\n }\n : undefined,\n metadata: { synthetic: true },\n }));\n\n const toolCallsFromUsage = params.toolsUsed.reduce(\n (sum, tool) => sum + Math.max(tool.skillCalls, 0),\n 0\n );\n const toolCallsFromStatus = params.statusTimeline.filter(\n (entry) => entry.status === \"tool-complete\"\n ).length;\n const toolCalls = toolCallsFromUsage > 0 ? toolCallsFromUsage : toolCallsFromStatus;\n\n const retryCount = params.statusTimeline.filter((entry) =>\n /(retry|fix|reflect|recover)/i.test(entry.status)\n ).length;\n const completionChecks = params.statusTimeline.filter((entry) =>\n /complet/i.test(entry.status)\n ).length;\n\n return {\n summary: {\n toolCalls,\n retryCount,\n selfHealCount: retryCount,\n fallbackCount: 0,\n failureCount: 0,\n recoveryCount: 0,\n completionChecks,\n loopCount: retryCount,\n },\n timeline,\n source: \"sdk-fallback\",\n synthetic: true,\n reason: \"backend_trace_missing\",\n durationMs: params.durationMs,\n };\n }\n\n private mergeDeveloperTrace(\n first: QueryDeveloperTrace | undefined,\n second: QueryDeveloperTrace | undefined\n ): QueryDeveloperTrace | undefined {\n if (!first) return second;\n if (!second) return first;\n\n const firstTimeline = Array.isArray(first.timeline) ? first.timeline : [];\n const secondTimeline = Array.isArray(second.timeline) ? second.timeline : [];\n const mergedTimeline = [...firstTimeline, ...secondTimeline];\n\n return {\n ...first,\n ...second,\n summary: {\n ...(typeof first.summary === \"object\" && first.summary ? first.summary : {}),\n ...(typeof second.summary === \"object\" && second.summary\n ? second.summary\n : {}),\n },\n ...(mergedTimeline.length > 0 ? { timeline: mergedTimeline } : {}),\n };\n }\n\n private parseStreamEvent(rawData: string): QueryStreamEvent | undefined {\n const parsed = JSON.parse(rawData) as unknown;\n if (!parsed || typeof parsed !== \"object\") {\n return undefined;\n }\n\n const event = parsed as QueryStreamEvent;\n if (typeof (event as { type?: unknown }).type !== \"string\") {\n return undefined;\n }\n\n return event;\n }\n\n /**\n * Run an agentic query and wait for the full response.\n *\n * The server discovers relevant tools (or uses the ones you specify),\n * executes the discovery-first pipeline (up to 100 MCP calls per tool),\n * and returns an AI-synthesized answer. Payment is settled after\n * successful execution via deferred settlement.\n *\n * @param options - Query options or a plain string question\n * @returns The complete query result with response text, tools used, and cost\n *\n * @throws {ContextError} With code `no_wallet` if wallet not set up\n * @throws {ContextError} With code `insufficient_allowance` if spending cap not set\n * @throws {ContextError} With code `payment_failed` if payment settlement fails\n * @throws {ContextError} With code `execution_failed` if the agentic pipeline fails\n *\n * @example\n * ```typescript\n * // Simple question — server discovers tools automatically\n * const answer = await client.query.run(\"What are the top whale movements on Base?\");\n * console.log(answer.response); // AI-synthesized answer\n * console.log(answer.toolsUsed); // Which tools were used\n * console.log(answer.cost); // Cost breakdown\n *\n * // With specific tools (Manual Mode)\n * const answer = await client.query.run({\n * query: \"Analyze whale activity\",\n * tools: [\"tool-uuid-1\", \"tool-uuid-2\"],\n * });\n * ```\n */\n async run(options: QueryOptions | string): Promise<QueryResult> {\n const opts = typeof options === \"string\" ? { query: options } : options;\n let terminalError:\n | { error: string; code?: string; scope?: string; reasonCode?: string }\n | undefined;\n let finalResult: QueryResult | undefined;\n\n for await (const event of this.stream(opts)) {\n if (event.type === \"error\") {\n terminalError = {\n error: event.error,\n ...(event.code ? { code: event.code } : {}),\n ...(event.scope ? { scope: event.scope } : {}),\n ...(event.reasonCode ? { reasonCode: event.reasonCode } : {}),\n };\n continue;\n }\n\n if (event.type === \"done\") {\n finalResult = event.result;\n }\n }\n\n if (finalResult) {\n return finalResult;\n }\n\n if (terminalError) {\n throw new ContextError(terminalError.error, terminalError.code);\n }\n\n throw new ContextError(\"Streaming query ended before done event\");\n }\n\n /**\n * Run an agentic query with streaming. Returns an async iterable that\n * yields events as the server processes the query in real-time.\n *\n * Event types:\n * - `tool-status` — A tool started executing or changed status\n * - `text-delta` — A chunk of the AI response text\n * - `developer-trace` — Runtime trace metadata (when includeDeveloperTrace=true)\n * - `error` — A structured query/runtime error emitted before stream completion\n * - `done` — The full response is complete (includes final `QueryResult`)\n *\n * @param options - Query options or a plain string question\n * @returns An async iterable of stream events\n *\n * @example\n * ```typescript\n * for await (const event of client.query.stream(\"What are the top whale movements?\")) {\n * switch (event.type) {\n * case \"tool-status\":\n * console.log(`Tool ${event.tool.name}: ${event.status}`);\n * break;\n * case \"text-delta\":\n * process.stdout.write(event.delta);\n * break;\n * case \"developer-trace\":\n * console.log(\"Trace summary:\", event.trace.summary);\n * break;\n * case \"done\":\n * console.log(\"\\nCost:\", event.result.cost.totalCostUsd);\n * break;\n * case \"error\":\n * console.error(\"Stream error:\", event.error);\n * break;\n * }\n * }\n * ```\n */\n async *stream(\n options: QueryOptions | string\n ): AsyncGenerator<QueryStreamEvent> {\n const opts = typeof options === \"string\" ? { query: options } : options;\n const headers = opts.idempotencyKey\n ? { \"Idempotency-Key\": opts.idempotencyKey }\n : undefined;\n\n const response = await this.client._fetchRaw(\"/api/v1/query\", {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n query: opts.query,\n tools: opts.tools,\n resumeFrom: opts.resumeFrom,\n forkFrom: opts.forkFrom,\n answerModelId: opts.answerModelId,\n responseShape: opts.responseShape,\n favoritesOnly: opts.favoritesOnly,\n includeData: opts.includeData,\n includeDataUrl: opts.includeDataUrl,\n includeDeveloperTrace: opts.includeDeveloperTrace,\n stream: true,\n }),\n });\n\n const body = response.body;\n if (!body) {\n throw new ContextError(\"No response body for streaming query\");\n }\n\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n let aggregatedTrace: QueryDeveloperTrace | undefined;\n const statusTimeline: Array<{\n status: string;\n tool: { id: string; name: string };\n }> = [];\n\n const parseAndHydrateEvent = (\n rawData: string\n ): QueryStreamEvent | undefined => {\n const event = this.parseStreamEvent(rawData);\n if (!event) {\n return undefined;\n }\n\n if (event.type === \"developer-trace\") {\n aggregatedTrace = this.mergeDeveloperTrace(aggregatedTrace, event.trace);\n return event;\n }\n\n if (event.type === \"tool-status\") {\n statusTimeline.push({\n status: event.status,\n tool: {\n id: event.tool.id,\n name: event.tool.name,\n },\n });\n return event;\n }\n\n if (event.type === \"done\") {\n const normalizedResult = this.normalizeResult(event.result);\n let mergedTrace = this.mergeDeveloperTrace(\n aggregatedTrace,\n normalizedResult.developerTrace\n );\n if (!mergedTrace && opts.includeDeveloperTrace) {\n mergedTrace =\n statusTimeline.length > 0\n ? this.buildSyntheticTraceFromStreamStatus({\n statusTimeline,\n toolsUsed: normalizedResult.toolsUsed,\n durationMs: normalizedResult.durationMs,\n })\n : this.buildSyntheticTraceFromRunResult({\n toolsUsed: normalizedResult.toolsUsed,\n durationMs: normalizedResult.durationMs,\n });\n }\n if (mergedTrace) {\n normalizedResult.developerTrace = mergedTrace;\n }\n event.result = normalizedResult;\n }\n\n return event;\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.startsWith(\"data: \")) {\n const data = trimmed.slice(6);\n if (data === \"[DONE]\") return;\n try {\n const event = parseAndHydrateEvent(data);\n if (event) {\n yield event;\n }\n } catch {\n // Skip malformed SSE events\n }\n }\n }\n }\n\n // Process any remaining buffer\n if (buffer.trim().startsWith(\"data: \")) {\n const data = buffer.trim().slice(6);\n if (data !== \"[DONE]\") {\n try {\n const event = parseAndHydrateEvent(data);\n if (event) {\n yield event;\n }\n } catch {\n // Skip malformed SSE events\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n}\n","import type { ContextClientOptions } from \"./types.js\";\nimport { ContextError } from \"./types.js\";\nimport { Developer } from \"./resources/developer.js\";\nimport { Discovery } from \"./resources/discovery.js\";\nimport { Tools } from \"./resources/tools.js\";\nimport { Query } from \"./resources/query.js\";\n\nconst DEFAULT_BASE_URL = \"https://www.ctxprotocol.com\";\nconst DEFAULT_REQUEST_TIMEOUT_MS = 300_000;\nconst DEFAULT_STREAM_TIMEOUT_MS = 600_000;\n\n/**\n * The official TypeScript client for the Context Protocol.\n *\n * Use this client to discover and execute AI tools programmatically.\n *\n * @example\n * ```typescript\n * import { ContextClient } from \"@contextprotocol/client\";\n *\n * const client = new ContextClient({\n * apiKey: \"sk_live_...\"\n * });\n *\n * // Pay-per-request: Execute a specific tool\n * const result = await client.tools.execute({\n * toolId: \"tool-uuid\",\n * toolName: \"get_gas_prices\",\n * args: { chainId: 1 }\n * });\n *\n * // Pay-per-response: Ask a question, get a curated answer\n * const answer = await client.query.run(\"What are the top whale movements on Base?\");\n * console.log(answer.response);\n * ```\n */\nexport class ContextClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly requestTimeoutMs: number;\n private readonly streamTimeoutMs: number;\n private _closed = false;\n\n /**\n * Developer resource for managing tool listings (contributor/developer concerns).\n */\n public readonly developer: Developer;\n\n /**\n * Discovery resource for searching tools\n */\n public readonly discovery: Discovery;\n\n /**\n * Tools resource for executing tools (pay-per-request)\n */\n public readonly tools: Tools;\n\n /**\n * Query resource for agentic queries (pay-per-response).\n *\n * Unlike `tools.execute()` which calls a single tool once, `query` sends\n * a natural-language question and lets the server handle discovery,\n * metadata scout, iterative execution, and AI synthesis —\n * one flat fee.\n */\n public readonly query: Query;\n\n /**\n * Creates a new Context Protocol client\n *\n * @param options - Client configuration options\n * @param options.apiKey - Your Context Protocol API key (format: sk_live_...)\n * @param options.baseUrl - Optional base URL override (defaults to https://www.ctxprotocol.com)\n * @param options.requestTimeoutMs - Optional timeout for non-streaming requests (default 300000ms)\n * @param options.streamTimeoutMs - Optional timeout for establishing stream requests (default 600000ms)\n */\n constructor(options: ContextClientOptions) {\n if (!options.apiKey) {\n throw new ContextError(\"API key is required\");\n }\n\n const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n const streamTimeoutMs = options.streamTimeoutMs ?? DEFAULT_STREAM_TIMEOUT_MS;\n\n if (!Number.isFinite(requestTimeoutMs) || requestTimeoutMs <= 0) {\n throw new ContextError(\"requestTimeoutMs must be a positive number\");\n }\n\n if (!Number.isFinite(streamTimeoutMs) || streamTimeoutMs <= 0) {\n throw new ContextError(\"streamTimeoutMs must be a positive number\");\n }\n\n this.apiKey = options.apiKey;\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n this.requestTimeoutMs = requestTimeoutMs;\n this.streamTimeoutMs = streamTimeoutMs;\n\n // Initialize resources\n this.developer = new Developer(this);\n this.discovery = new Discovery(this);\n this.tools = new Tools(this);\n this.query = new Query(this);\n }\n\n /**\n * Close the client and clean up resources.\n * After calling close(), any in-flight requests may be aborted.\n */\n close(): void {\n this._closed = true;\n }\n\n /**\n * Internal method for making authenticated HTTP requests\n * Includes timeout and retry with exponential backoff for transient errors\n *\n * @internal\n */\n async _fetch<T>(\n endpoint: string,\n options: RequestInit = {},\n fetchOptions?: { retry?: boolean }\n ): Promise<T> {\n if (this._closed) {\n throw new ContextError(\"Client has been closed\");\n }\n\n const url = `${this.baseUrl}${endpoint}`;\n const maxRetries = 3;\n const timeoutMs = this.requestTimeoutMs;\n const method = (options.method ?? \"GET\").toUpperCase();\n const requestHeaders = new Headers(options.headers);\n const canRetryRequest =\n fetchOptions?.retry === false\n ? false\n : method === \"GET\" ||\n method === \"HEAD\" ||\n method === \"OPTIONS\" ||\n requestHeaders.has(\"Idempotency-Key\");\n\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n const mergedHeaders = new Headers(requestHeaders);\n if (!mergedHeaders.has(\"Content-Type\")) {\n mergedHeaders.set(\"Content-Type\", \"application/json\");\n }\n mergedHeaders.set(\"Authorization\", `Bearer ${this.apiKey}`);\n\n try {\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n headers: mergedHeaders,\n });\n\n clearTimeout(timeout);\n\n if (!response.ok) {\n // Retry on 5xx server errors\n if (response.status >= 500 && canRetryRequest && attempt < maxRetries) {\n const delay = Math.min(1000 * 2 ** attempt, 10_000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n continue;\n }\n\n let errorMessage = `HTTP ${response.status}: ${response.statusText}`;\n let errorCode: string | undefined;\n let helpUrl: string | undefined;\n\n try {\n const errorBody = await response.json();\n if (errorBody.error) {\n errorMessage = errorBody.error;\n errorCode = errorBody.code;\n helpUrl = errorBody.helpUrl;\n }\n } catch {\n // Use default error message if JSON parsing fails\n }\n\n throw new ContextError(errorMessage, errorCode, response.status, helpUrl);\n }\n\n try {\n return (await response.json()) as T;\n } catch (error) {\n const parseError = error instanceof Error ? error : new Error(String(error));\n throw new ContextError(\n `Failed to parse JSON response: ${parseError.message}`,\n undefined,\n response.status\n );\n }\n } catch (error) {\n clearTimeout(timeout);\n\n if (error instanceof ContextError) {\n throw error;\n }\n\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Retry on network errors and timeouts\n const isRetryable =\n lastError.name === \"AbortError\" ||\n lastError.message.includes(\"fetch failed\") ||\n lastError.message.includes(\"ECONNRESET\") ||\n lastError.message.includes(\"ETIMEDOUT\");\n\n if (isRetryable && canRetryRequest && attempt < maxRetries) {\n const delay = Math.min(1000 * 2 ** attempt, 10_000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n continue;\n }\n\n if (lastError.name === \"AbortError\") {\n throw new ContextError(\n `Request timed out after ${timeoutMs / 1000}s`,\n undefined,\n 408\n );\n }\n\n throw new ContextError(\n lastError.message,\n undefined,\n undefined\n );\n }\n }\n\n throw lastError ?? new ContextError(\"Request failed after retries\");\n }\n\n /**\n * Internal method for making authenticated HTTP requests that returns\n * the raw Response object. Used for streaming endpoints (SSE).\n * Includes a configurable timeout for stream setup.\n *\n * @internal\n */\n async _fetchRaw(endpoint: string, options: RequestInit = {}): Promise<Response> {\n if (this._closed) {\n throw new ContextError(\"Client has been closed\");\n }\n\n const url = `${this.baseUrl}${endpoint}`;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.streamTimeoutMs);\n\n let response: Response;\n try {\n response = await fetch(url, {\n ...options,\n signal: controller.signal,\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n ...options.headers,\n },\n });\n } catch (error) {\n clearTimeout(timeout);\n const lastError = error instanceof Error ? error : new Error(String(error));\n if (lastError.name === \"AbortError\") {\n throw new ContextError(\n `Streaming request timed out after ${this.streamTimeoutMs / 1000}s`,\n undefined,\n 408\n );\n }\n throw new ContextError(lastError.message);\n }\n\n clearTimeout(timeout);\n\n if (!response.ok) {\n let errorMessage = `HTTP ${response.status}: ${response.statusText}`;\n let errorCode: string | undefined;\n let helpUrl: string | undefined;\n\n try {\n const errorBody = await response.json();\n if (errorBody.error) {\n errorMessage = errorBody.error;\n errorCode = errorBody.code;\n helpUrl = errorBody.helpUrl;\n }\n } catch {\n // Use default error message if JSON parsing fails\n }\n\n throw new ContextError(errorMessage, errorCode, response.status, helpUrl);\n }\n\n return response;\n }\n}\n"]}
|