@ctxprotocol/sdk 0.6.0 → 0.8.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 +136 -23
- package/dist/client/index.cjs +211 -4
- package/dist/client/index.cjs.map +1 -1
- package/dist/client/index.d.cts +228 -11
- package/dist/client/index.d.ts +228 -11
- package/dist/client/index.js +211 -5
- package/dist/client/index.js.map +1 -1
- package/dist/index.cjs +211 -4
- 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 +211 -5
- package/dist/index.js.map +1 -1
- package/package.json +5 -2
package/dist/client/index.js
CHANGED
|
@@ -73,8 +73,8 @@ var Tools = class {
|
|
|
73
73
|
* @returns The execution result with the tool's output data
|
|
74
74
|
*
|
|
75
75
|
* @throws {ContextError} With code `no_wallet` if wallet not set up
|
|
76
|
-
* @throws {ContextError} With code `insufficient_allowance` if
|
|
77
|
-
* @throws {ContextError} With code `payment_failed` if
|
|
76
|
+
* @throws {ContextError} With code `insufficient_allowance` if spending cap not set
|
|
77
|
+
* @throws {ContextError} With code `payment_failed` if payment settlement fails
|
|
78
78
|
* @throws {ContextError} With code `execution_failed` if tool execution fails
|
|
79
79
|
*
|
|
80
80
|
* @example
|
|
@@ -95,11 +95,13 @@ var Tools = class {
|
|
|
95
95
|
* ```
|
|
96
96
|
*/
|
|
97
97
|
async execute(options) {
|
|
98
|
-
const { toolId, toolName, args } = options;
|
|
98
|
+
const { toolId, toolName, args, idempotencyKey } = options;
|
|
99
|
+
const headers = idempotencyKey ? { "Idempotency-Key": idempotencyKey } : void 0;
|
|
99
100
|
const response = await this.client._fetch(
|
|
100
101
|
"/api/v1/tools/execute",
|
|
101
102
|
{
|
|
102
103
|
method: "POST",
|
|
104
|
+
headers,
|
|
103
105
|
body: JSON.stringify({ toolId, toolName, args })
|
|
104
106
|
}
|
|
105
107
|
);
|
|
@@ -123,6 +125,165 @@ var Tools = class {
|
|
|
123
125
|
}
|
|
124
126
|
};
|
|
125
127
|
|
|
128
|
+
// src/client/resources/query.ts
|
|
129
|
+
var Query = class {
|
|
130
|
+
constructor(client) {
|
|
131
|
+
this.client = client;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Run an agentic query and wait for the full response.
|
|
135
|
+
*
|
|
136
|
+
* The server discovers relevant tools (or uses the ones you specify),
|
|
137
|
+
* executes the full agentic pipeline (up to 100 MCP calls per tool),
|
|
138
|
+
* and returns an AI-synthesized answer. Payment is settled after
|
|
139
|
+
* successful execution via deferred settlement.
|
|
140
|
+
*
|
|
141
|
+
* @param options - Query options or a plain string question
|
|
142
|
+
* @returns The complete query result with response text, tools used, and cost
|
|
143
|
+
*
|
|
144
|
+
* @throws {ContextError} With code `no_wallet` if wallet not set up
|
|
145
|
+
* @throws {ContextError} With code `insufficient_allowance` if spending cap not set
|
|
146
|
+
* @throws {ContextError} With code `payment_failed` if payment settlement fails
|
|
147
|
+
* @throws {ContextError} With code `execution_failed` if the agentic pipeline fails
|
|
148
|
+
*
|
|
149
|
+
* @example
|
|
150
|
+
* ```typescript
|
|
151
|
+
* // Simple question — server discovers tools automatically
|
|
152
|
+
* const answer = await client.query.run("What are the top whale movements on Base?");
|
|
153
|
+
* console.log(answer.response); // AI-synthesized answer
|
|
154
|
+
* console.log(answer.toolsUsed); // Which tools were used
|
|
155
|
+
* console.log(answer.cost); // Cost breakdown
|
|
156
|
+
*
|
|
157
|
+
* // With specific tools (Manual Mode)
|
|
158
|
+
* const answer = await client.query.run({
|
|
159
|
+
* query: "Analyze whale activity",
|
|
160
|
+
* tools: ["tool-uuid-1", "tool-uuid-2"],
|
|
161
|
+
* });
|
|
162
|
+
* ```
|
|
163
|
+
*/
|
|
164
|
+
async run(options) {
|
|
165
|
+
const opts = typeof options === "string" ? { query: options } : options;
|
|
166
|
+
const headers = opts.idempotencyKey ? { "Idempotency-Key": opts.idempotencyKey } : void 0;
|
|
167
|
+
const response = await this.client._fetch(
|
|
168
|
+
"/api/v1/query",
|
|
169
|
+
{
|
|
170
|
+
method: "POST",
|
|
171
|
+
headers,
|
|
172
|
+
body: JSON.stringify({
|
|
173
|
+
query: opts.query,
|
|
174
|
+
tools: opts.tools,
|
|
175
|
+
modelId: opts.modelId,
|
|
176
|
+
includeData: opts.includeData,
|
|
177
|
+
includeDataUrl: opts.includeDataUrl,
|
|
178
|
+
stream: false
|
|
179
|
+
})
|
|
180
|
+
}
|
|
181
|
+
);
|
|
182
|
+
if ("error" in response) {
|
|
183
|
+
throw new ContextError(
|
|
184
|
+
response.error,
|
|
185
|
+
response.code,
|
|
186
|
+
void 0,
|
|
187
|
+
response.helpUrl
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
if (response.success) {
|
|
191
|
+
return {
|
|
192
|
+
response: response.response,
|
|
193
|
+
toolsUsed: response.toolsUsed,
|
|
194
|
+
cost: response.cost,
|
|
195
|
+
durationMs: response.durationMs,
|
|
196
|
+
data: response.data,
|
|
197
|
+
dataUrl: response.dataUrl
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
throw new ContextError("Unexpected response format from query API");
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Run an agentic query with streaming. Returns an async iterable that
|
|
204
|
+
* yields events as the server processes the query in real-time.
|
|
205
|
+
*
|
|
206
|
+
* Event types:
|
|
207
|
+
* - `tool-status` — A tool started executing or changed status
|
|
208
|
+
* - `text-delta` — A chunk of the AI response text
|
|
209
|
+
* - `done` — The full response is complete (includes final `QueryResult`)
|
|
210
|
+
*
|
|
211
|
+
* @param options - Query options or a plain string question
|
|
212
|
+
* @returns An async iterable of stream events
|
|
213
|
+
*
|
|
214
|
+
* @example
|
|
215
|
+
* ```typescript
|
|
216
|
+
* for await (const event of client.query.stream("What are the top whale movements?")) {
|
|
217
|
+
* switch (event.type) {
|
|
218
|
+
* case "tool-status":
|
|
219
|
+
* console.log(`Tool ${event.tool.name}: ${event.status}`);
|
|
220
|
+
* break;
|
|
221
|
+
* case "text-delta":
|
|
222
|
+
* process.stdout.write(event.delta);
|
|
223
|
+
* break;
|
|
224
|
+
* case "done":
|
|
225
|
+
* console.log("\nCost:", event.result.cost.totalCostUsd);
|
|
226
|
+
* break;
|
|
227
|
+
* }
|
|
228
|
+
* }
|
|
229
|
+
* ```
|
|
230
|
+
*/
|
|
231
|
+
async *stream(options) {
|
|
232
|
+
const opts = typeof options === "string" ? { query: options } : options;
|
|
233
|
+
const headers = opts.idempotencyKey ? { "Idempotency-Key": opts.idempotencyKey } : void 0;
|
|
234
|
+
const response = await this.client._fetchRaw("/api/v1/query", {
|
|
235
|
+
method: "POST",
|
|
236
|
+
headers,
|
|
237
|
+
body: JSON.stringify({
|
|
238
|
+
query: opts.query,
|
|
239
|
+
tools: opts.tools,
|
|
240
|
+
modelId: opts.modelId,
|
|
241
|
+
includeData: opts.includeData,
|
|
242
|
+
includeDataUrl: opts.includeDataUrl,
|
|
243
|
+
stream: true
|
|
244
|
+
})
|
|
245
|
+
});
|
|
246
|
+
const body = response.body;
|
|
247
|
+
if (!body) {
|
|
248
|
+
throw new ContextError("No response body for streaming query");
|
|
249
|
+
}
|
|
250
|
+
const reader = body.getReader();
|
|
251
|
+
const decoder = new TextDecoder();
|
|
252
|
+
let buffer = "";
|
|
253
|
+
try {
|
|
254
|
+
while (true) {
|
|
255
|
+
const { done, value } = await reader.read();
|
|
256
|
+
if (done) break;
|
|
257
|
+
buffer += decoder.decode(value, { stream: true });
|
|
258
|
+
const lines = buffer.split("\n");
|
|
259
|
+
buffer = lines.pop() ?? "";
|
|
260
|
+
for (const line of lines) {
|
|
261
|
+
const trimmed = line.trim();
|
|
262
|
+
if (trimmed.startsWith("data: ")) {
|
|
263
|
+
const data = trimmed.slice(6);
|
|
264
|
+
if (data === "[DONE]") return;
|
|
265
|
+
try {
|
|
266
|
+
yield JSON.parse(data);
|
|
267
|
+
} catch {
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (buffer.trim().startsWith("data: ")) {
|
|
273
|
+
const data = buffer.trim().slice(6);
|
|
274
|
+
if (data !== "[DONE]") {
|
|
275
|
+
try {
|
|
276
|
+
yield JSON.parse(data);
|
|
277
|
+
} catch {
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
} finally {
|
|
282
|
+
reader.releaseLock();
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
|
|
126
287
|
// src/client/client.ts
|
|
127
288
|
var ContextClient = class {
|
|
128
289
|
apiKey;
|
|
@@ -133,9 +294,17 @@ var ContextClient = class {
|
|
|
133
294
|
*/
|
|
134
295
|
discovery;
|
|
135
296
|
/**
|
|
136
|
-
* Tools resource for executing tools
|
|
297
|
+
* Tools resource for executing tools (pay-per-request)
|
|
137
298
|
*/
|
|
138
299
|
tools;
|
|
300
|
+
/**
|
|
301
|
+
* Query resource for agentic queries (pay-per-response).
|
|
302
|
+
*
|
|
303
|
+
* Unlike `tools.execute()` which calls a single tool once, `query` sends
|
|
304
|
+
* a natural-language question and lets the server handle tool discovery,
|
|
305
|
+
* multi-tool orchestration, self-healing, and AI synthesis — one flat fee.
|
|
306
|
+
*/
|
|
307
|
+
query;
|
|
139
308
|
/**
|
|
140
309
|
* Creates a new Context Protocol client
|
|
141
310
|
*
|
|
@@ -151,6 +320,7 @@ var ContextClient = class {
|
|
|
151
320
|
this.baseUrl = (options.baseUrl ?? "https://ctxprotocol.com").replace(/\/$/, "");
|
|
152
321
|
this.discovery = new Discovery(this);
|
|
153
322
|
this.tools = new Tools(this);
|
|
323
|
+
this.query = new Query(this);
|
|
154
324
|
}
|
|
155
325
|
/**
|
|
156
326
|
* Close the client and clean up resources.
|
|
@@ -236,8 +406,44 @@ var ContextClient = class {
|
|
|
236
406
|
}
|
|
237
407
|
throw lastError ?? new ContextError("Request failed after retries");
|
|
238
408
|
}
|
|
409
|
+
/**
|
|
410
|
+
* Internal method for making authenticated HTTP requests that returns
|
|
411
|
+
* the raw Response object. Used for streaming endpoints (SSE).
|
|
412
|
+
*
|
|
413
|
+
* @internal
|
|
414
|
+
*/
|
|
415
|
+
async _fetchRaw(endpoint, options = {}) {
|
|
416
|
+
if (this._closed) {
|
|
417
|
+
throw new ContextError("Client has been closed");
|
|
418
|
+
}
|
|
419
|
+
const url = `${this.baseUrl}${endpoint}`;
|
|
420
|
+
const response = await fetch(url, {
|
|
421
|
+
...options,
|
|
422
|
+
headers: {
|
|
423
|
+
"Content-Type": "application/json",
|
|
424
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
425
|
+
...options.headers
|
|
426
|
+
}
|
|
427
|
+
});
|
|
428
|
+
if (!response.ok) {
|
|
429
|
+
let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
|
|
430
|
+
let errorCode;
|
|
431
|
+
let helpUrl;
|
|
432
|
+
try {
|
|
433
|
+
const errorBody = await response.json();
|
|
434
|
+
if (errorBody.error) {
|
|
435
|
+
errorMessage = errorBody.error;
|
|
436
|
+
errorCode = errorBody.code;
|
|
437
|
+
helpUrl = errorBody.helpUrl;
|
|
438
|
+
}
|
|
439
|
+
} catch {
|
|
440
|
+
}
|
|
441
|
+
throw new ContextError(errorMessage, errorCode, response.status, helpUrl);
|
|
442
|
+
}
|
|
443
|
+
return response;
|
|
444
|
+
}
|
|
239
445
|
};
|
|
240
446
|
|
|
241
|
-
export { ContextClient, ContextError, Discovery, Tools };
|
|
447
|
+
export { ContextClient, ContextError, Discovery, Query, Tools };
|
|
242
448
|
//# sourceMappingURL=index.js.map
|
|
243
449
|
//# sourceMappingURL=index.js.map
|
package/dist/client/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/client/types.ts","../../src/client/resources/discovery.ts","../../src/client/resources/tools.ts","../../src/client/client.ts"],"names":[],"mappings":";AAmMO,IAAM,YAAA,GAAN,MAAM,aAAA,SAAqB,KAAA,CAAM;AAAA,EACtC,W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\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://ctxprotocol.com\"\n */\n baseUrl?: string;\n}\n\n/**\n * An individual MCP tool exposed by a tool listing\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\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 /** 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\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/**\n * Successful execution response from the API\n */\nexport interface ExecuteApiSuccessResponse {\n success: true;\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 /** 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 /** Error code for programmatic handling */\n code?: ContextErrorCode;\n\n /** URL to help resolve the issue */\n helpUrl?: string;\n}\n\n/**\n * Raw API response from the execute endpoint\n */\nexport type ExecuteApiResponse = ExecuteApiSuccessResponse | ExecuteApiErrorResponse;\n\n/**\n * The resolved result returned to the user after SDK processing\n */\nexport interface ExecutionResult<T = unknown> {\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 /** Execution duration in milliseconds */\n durationMs: number;\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\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 { Tool, SearchResponse } 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 * Search for tools matching a query string\n *\n * @param query - The search query (e.g., \"gas prices\", \"nft metadata\")\n * @param limit - Maximum number of results (1-50, default 10)\n * @returns Array of matching tools\n *\n * @example\n * ```typescript\n * const tools = await client.discovery.search(\"gas prices\");\n * console.log(tools[0].name); // \"Gas Price Oracle\"\n * console.log(tools[0].mcpTools); // Available methods\n * ```\n */\n async search(query: string, limit?: number): Promise<Tool[]> {\n const params = new URLSearchParams();\n\n if (query) {\n params.set(\"q\", query);\n }\n\n if (limit !== undefined) {\n params.set(\"limit\", String(limit));\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(limit?: number): Promise<Tool[]> {\n return this.search(\"\", limit);\n }\n}\n","import type {\n ExecuteOptions,\n ExecuteApiResponse,\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 Auto Pay not enabled\n * @throws {ContextError} With code `payment_failed` if on-chain payment 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 { toolId, toolName, args } = options;\n\n const response = await this.client._fetch<ExecuteApiResponse>(\n \"/api/v1/tools/execute\",\n {\n method: \"POST\",\n body: JSON.stringify({ toolId, toolName, args }),\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 result: response.result as T,\n tool: response.tool,\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","import type { ContextClientOptions } from \"./types.js\";\nimport { ContextError } from \"./types.js\";\nimport { Discovery } from \"./resources/discovery.js\";\nimport { Tools } from \"./resources/tools.js\";\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 * // Discover tools\n * const tools = await client.discovery.search(\"gas prices\");\n *\n * // Execute a tool method\n * const result = await client.tools.execute({\n * toolId: tools[0].id,\n * toolName: tools[0].mcpTools[0].name,\n * args: { chainId: 1 }\n * });\n * ```\n */\nexport class ContextClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private _closed = false;\n\n /**\n * Discovery resource for searching tools\n */\n public readonly discovery: Discovery;\n\n /**\n * Tools resource for executing tools\n */\n public readonly tools: Tools;\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://ctxprotocol.com)\n */\n constructor(options: ContextClientOptions) {\n if (!options.apiKey) {\n throw new ContextError(\"API key is required\");\n }\n\n this.apiKey = options.apiKey;\n this.baseUrl = (options.baseUrl ?? \"https://ctxprotocol.com\").replace(/\\/$/, \"\");\n\n // Initialize resources\n this.discovery = new Discovery(this);\n this.tools = new Tools(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 (30s) and retry with exponential backoff for transient errors\n *\n * @internal\n */\n async _fetch<T>(endpoint: string, options: RequestInit = {}): 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 = 30_000;\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\n try {\n const 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\n clearTimeout(timeout);\n\n if (!response.ok) {\n // Retry on 5xx server errors\n if (response.status >= 500 && 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 return response.json() as Promise<T>;\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 && 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"]}
|
|
1
|
+
{"version":3,"sources":["../../src/client/types.ts","../../src/client/resources/discovery.ts","../../src/client/resources/tools.ts","../../src/client/resources/query.ts","../../src/client/client.ts"],"names":[],"mappings":";AAmWO,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,CAAA,UAAA,GAAA,UAAA;AACA,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,aAAA,CAAa,SAAS,CAAA;AAAA,EACpD;AACF;;;ACxWO,IAAM,YAAN,MAAgB;AAAA,EACrB,YAAoB,MAAA,EAAuB;AAAvB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAAwB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgB5C,MAAM,MAAA,CAAO,KAAA,EAAe,KAAA,EAAiC;AAC3D,IAAA,MAAM,MAAA,GAAS,IAAI,eAAA,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e,CAAA,OAAA,EAAU,IAAA,CAAK,MAAM,CAAA,CAAA;AAAA,QACpC,GAAG,OAAA,CAAQ;AAAA;AACb,KACD,CAAA;AAED,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.js","sourcesContent":["/**\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://ctxprotocol.com\"\n */\n baseUrl?: string;\n}\n\n/**\n * An individual MCP tool exposed by a tool listing\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\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 /** 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\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\n/**\n * Successful execution response from the API\n */\nexport interface ExecuteApiSuccessResponse {\n success: true;\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 /** 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 /** Error code for programmatic handling */\n code?: ContextErrorCode;\n\n /** URL to help resolve the issue */\n helpUrl?: string;\n}\n\n/**\n * Raw API response from the execute endpoint\n */\nexport type ExecuteApiResponse = ExecuteApiSuccessResponse | ExecuteApiErrorResponse;\n\n/**\n * The resolved result returned to the user after SDK processing\n */\nexport interface ExecutionResult<T = unknown> {\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 /** Execution duration in milliseconds */\n durationMs: number;\n}\n\n// ---------------------------------------------------------------------------\n// Query types (pay-per-response / agentic mode)\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 tool discovery,\n * multi-tool orchestration, self-healing retries, and AI synthesis.\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 * Optional model ID for query orchestration/synthesis.\n * Supported IDs are published by the Context API.\n */\n modelId?: string;\n\n /**\n * Include execution data inline in the query response.\n * Useful for headless agents that need raw structured outputs.\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 * Optional idempotency key (UUID recommended).\n * Reuse the same key when retrying the same logical request.\n */\n idempotencyKey?: string;\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 * The resolved result of a pay-per-response query\n */\nexport interface QueryResult {\n /** The AI-synthesized response text */\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\n/**\n * Successful response from the /api/v1/query endpoint\n */\nexport interface QueryApiSuccessResponse {\n success: true;\n response: string;\n toolsUsed: QueryToolUsage[];\n cost: QueryCost;\n durationMs: number;\n data?: unknown;\n dataUrl?: string;\n}\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 full response is complete */\nexport interface QueryStreamDoneEvent {\n type: \"done\";\n result: QueryResult;\n}\n\n/**\n * Union of all events emitted during a streaming query\n */\nexport type QueryStreamEvent =\n | QueryStreamToolStatusEvent\n | QueryStreamTextDeltaEvent\n | QueryStreamDoneEvent;\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\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 { Tool, SearchResponse } 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 * Search for tools matching a query string\n *\n * @param query - The search query (e.g., \"gas prices\", \"nft metadata\")\n * @param limit - Maximum number of results (1-50, default 10)\n * @returns Array of matching tools\n *\n * @example\n * ```typescript\n * const tools = await client.discovery.search(\"gas prices\");\n * console.log(tools[0].name); // \"Gas Price Oracle\"\n * console.log(tools[0].mcpTools); // Available methods\n * ```\n */\n async search(query: string, limit?: number): Promise<Tool[]> {\n const params = new URLSearchParams();\n\n if (query) {\n params.set(\"q\", query);\n }\n\n if (limit !== undefined) {\n params.set(\"limit\", String(limit));\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(limit?: number): Promise<Tool[]> {\n return this.search(\"\", limit);\n }\n}\n","import type {\n ExecuteOptions,\n ExecuteApiResponse,\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 { toolId, toolName, args, idempotencyKey } = 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({ toolId, toolName, args }),\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 result: response.result as T,\n tool: response.tool,\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","import type {\n QueryOptions,\n QueryApiResponse,\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 tool discovery, multi-tool orchestration, self-healing retries,\n * completeness checks, and AI 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 /**\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 full agentic 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 const headers = opts.idempotencyKey\n ? { \"Idempotency-Key\": opts.idempotencyKey }\n : undefined;\n\n const response = await this.client._fetch<QueryApiResponse>(\n \"/api/v1/query\",\n {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n query: opts.query,\n tools: opts.tools,\n modelId: opts.modelId,\n includeData: opts.includeData,\n includeDataUrl: opts.includeDataUrl,\n stream: false,\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,\n response.helpUrl\n );\n }\n\n // Handle success response\n if (response.success) {\n return {\n response: response.response,\n toolsUsed: response.toolsUsed,\n cost: response.cost,\n durationMs: response.durationMs,\n data: response.data,\n dataUrl: response.dataUrl,\n };\n }\n\n throw new ContextError(\"Unexpected response format from query API\");\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 * - `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 \"done\":\n * console.log(\"\\nCost:\", event.result.cost.totalCostUsd);\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 modelId: opts.modelId,\n includeData: opts.includeData,\n includeDataUrl: opts.includeDataUrl,\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\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 yield JSON.parse(data) as QueryStreamEvent;\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 yield JSON.parse(data) as QueryStreamEvent;\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 { Discovery } from \"./resources/discovery.js\";\nimport { Tools } from \"./resources/tools.js\";\nimport { Query } from \"./resources/query.js\";\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 _closed = false;\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 tool discovery,\n * multi-tool orchestration, self-healing, and AI synthesis — 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://ctxprotocol.com)\n */\n constructor(options: ContextClientOptions) {\n if (!options.apiKey) {\n throw new ContextError(\"API key is required\");\n }\n\n this.apiKey = options.apiKey;\n this.baseUrl = (options.baseUrl ?? \"https://ctxprotocol.com\").replace(/\\/$/, \"\");\n\n // Initialize resources\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 (30s) and retry with exponential backoff for transient errors\n *\n * @internal\n */\n async _fetch<T>(endpoint: string, options: RequestInit = {}): 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 = 30_000;\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\n try {\n const 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\n clearTimeout(timeout);\n\n if (!response.ok) {\n // Retry on 5xx server errors\n if (response.status >= 500 && 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 return response.json() as Promise<T>;\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 && 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 *\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\n const response = await fetch(url, {\n ...options,\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n ...options.headers,\n },\n });\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"]}
|
package/dist/index.cjs
CHANGED
|
@@ -77,8 +77,8 @@ var Tools = class {
|
|
|
77
77
|
* @returns The execution result with the tool's output data
|
|
78
78
|
*
|
|
79
79
|
* @throws {ContextError} With code `no_wallet` if wallet not set up
|
|
80
|
-
* @throws {ContextError} With code `insufficient_allowance` if
|
|
81
|
-
* @throws {ContextError} With code `payment_failed` if
|
|
80
|
+
* @throws {ContextError} With code `insufficient_allowance` if spending cap not set
|
|
81
|
+
* @throws {ContextError} With code `payment_failed` if payment settlement fails
|
|
82
82
|
* @throws {ContextError} With code `execution_failed` if tool execution fails
|
|
83
83
|
*
|
|
84
84
|
* @example
|
|
@@ -99,11 +99,13 @@ var Tools = class {
|
|
|
99
99
|
* ```
|
|
100
100
|
*/
|
|
101
101
|
async execute(options) {
|
|
102
|
-
const { toolId, toolName, args } = options;
|
|
102
|
+
const { toolId, toolName, args, idempotencyKey } = options;
|
|
103
|
+
const headers = idempotencyKey ? { "Idempotency-Key": idempotencyKey } : void 0;
|
|
103
104
|
const response = await this.client._fetch(
|
|
104
105
|
"/api/v1/tools/execute",
|
|
105
106
|
{
|
|
106
107
|
method: "POST",
|
|
108
|
+
headers,
|
|
107
109
|
body: JSON.stringify({ toolId, toolName, args })
|
|
108
110
|
}
|
|
109
111
|
);
|
|
@@ -127,6 +129,165 @@ var Tools = class {
|
|
|
127
129
|
}
|
|
128
130
|
};
|
|
129
131
|
|
|
132
|
+
// src/client/resources/query.ts
|
|
133
|
+
var Query = class {
|
|
134
|
+
constructor(client) {
|
|
135
|
+
this.client = client;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Run an agentic query and wait for the full response.
|
|
139
|
+
*
|
|
140
|
+
* The server discovers relevant tools (or uses the ones you specify),
|
|
141
|
+
* executes the full agentic pipeline (up to 100 MCP calls per tool),
|
|
142
|
+
* and returns an AI-synthesized answer. Payment is settled after
|
|
143
|
+
* successful execution via deferred settlement.
|
|
144
|
+
*
|
|
145
|
+
* @param options - Query options or a plain string question
|
|
146
|
+
* @returns The complete query result with response text, tools used, and cost
|
|
147
|
+
*
|
|
148
|
+
* @throws {ContextError} With code `no_wallet` if wallet not set up
|
|
149
|
+
* @throws {ContextError} With code `insufficient_allowance` if spending cap not set
|
|
150
|
+
* @throws {ContextError} With code `payment_failed` if payment settlement fails
|
|
151
|
+
* @throws {ContextError} With code `execution_failed` if the agentic pipeline fails
|
|
152
|
+
*
|
|
153
|
+
* @example
|
|
154
|
+
* ```typescript
|
|
155
|
+
* // Simple question — server discovers tools automatically
|
|
156
|
+
* const answer = await client.query.run("What are the top whale movements on Base?");
|
|
157
|
+
* console.log(answer.response); // AI-synthesized answer
|
|
158
|
+
* console.log(answer.toolsUsed); // Which tools were used
|
|
159
|
+
* console.log(answer.cost); // Cost breakdown
|
|
160
|
+
*
|
|
161
|
+
* // With specific tools (Manual Mode)
|
|
162
|
+
* const answer = await client.query.run({
|
|
163
|
+
* query: "Analyze whale activity",
|
|
164
|
+
* tools: ["tool-uuid-1", "tool-uuid-2"],
|
|
165
|
+
* });
|
|
166
|
+
* ```
|
|
167
|
+
*/
|
|
168
|
+
async run(options) {
|
|
169
|
+
const opts = typeof options === "string" ? { query: options } : options;
|
|
170
|
+
const headers = opts.idempotencyKey ? { "Idempotency-Key": opts.idempotencyKey } : void 0;
|
|
171
|
+
const response = await this.client._fetch(
|
|
172
|
+
"/api/v1/query",
|
|
173
|
+
{
|
|
174
|
+
method: "POST",
|
|
175
|
+
headers,
|
|
176
|
+
body: JSON.stringify({
|
|
177
|
+
query: opts.query,
|
|
178
|
+
tools: opts.tools,
|
|
179
|
+
modelId: opts.modelId,
|
|
180
|
+
includeData: opts.includeData,
|
|
181
|
+
includeDataUrl: opts.includeDataUrl,
|
|
182
|
+
stream: false
|
|
183
|
+
})
|
|
184
|
+
}
|
|
185
|
+
);
|
|
186
|
+
if ("error" in response) {
|
|
187
|
+
throw new ContextError(
|
|
188
|
+
response.error,
|
|
189
|
+
response.code,
|
|
190
|
+
void 0,
|
|
191
|
+
response.helpUrl
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
if (response.success) {
|
|
195
|
+
return {
|
|
196
|
+
response: response.response,
|
|
197
|
+
toolsUsed: response.toolsUsed,
|
|
198
|
+
cost: response.cost,
|
|
199
|
+
durationMs: response.durationMs,
|
|
200
|
+
data: response.data,
|
|
201
|
+
dataUrl: response.dataUrl
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
throw new ContextError("Unexpected response format from query API");
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Run an agentic query with streaming. Returns an async iterable that
|
|
208
|
+
* yields events as the server processes the query in real-time.
|
|
209
|
+
*
|
|
210
|
+
* Event types:
|
|
211
|
+
* - `tool-status` — A tool started executing or changed status
|
|
212
|
+
* - `text-delta` — A chunk of the AI response text
|
|
213
|
+
* - `done` — The full response is complete (includes final `QueryResult`)
|
|
214
|
+
*
|
|
215
|
+
* @param options - Query options or a plain string question
|
|
216
|
+
* @returns An async iterable of stream events
|
|
217
|
+
*
|
|
218
|
+
* @example
|
|
219
|
+
* ```typescript
|
|
220
|
+
* for await (const event of client.query.stream("What are the top whale movements?")) {
|
|
221
|
+
* switch (event.type) {
|
|
222
|
+
* case "tool-status":
|
|
223
|
+
* console.log(`Tool ${event.tool.name}: ${event.status}`);
|
|
224
|
+
* break;
|
|
225
|
+
* case "text-delta":
|
|
226
|
+
* process.stdout.write(event.delta);
|
|
227
|
+
* break;
|
|
228
|
+
* case "done":
|
|
229
|
+
* console.log("\nCost:", event.result.cost.totalCostUsd);
|
|
230
|
+
* break;
|
|
231
|
+
* }
|
|
232
|
+
* }
|
|
233
|
+
* ```
|
|
234
|
+
*/
|
|
235
|
+
async *stream(options) {
|
|
236
|
+
const opts = typeof options === "string" ? { query: options } : options;
|
|
237
|
+
const headers = opts.idempotencyKey ? { "Idempotency-Key": opts.idempotencyKey } : void 0;
|
|
238
|
+
const response = await this.client._fetchRaw("/api/v1/query", {
|
|
239
|
+
method: "POST",
|
|
240
|
+
headers,
|
|
241
|
+
body: JSON.stringify({
|
|
242
|
+
query: opts.query,
|
|
243
|
+
tools: opts.tools,
|
|
244
|
+
modelId: opts.modelId,
|
|
245
|
+
includeData: opts.includeData,
|
|
246
|
+
includeDataUrl: opts.includeDataUrl,
|
|
247
|
+
stream: true
|
|
248
|
+
})
|
|
249
|
+
});
|
|
250
|
+
const body = response.body;
|
|
251
|
+
if (!body) {
|
|
252
|
+
throw new ContextError("No response body for streaming query");
|
|
253
|
+
}
|
|
254
|
+
const reader = body.getReader();
|
|
255
|
+
const decoder = new TextDecoder();
|
|
256
|
+
let buffer = "";
|
|
257
|
+
try {
|
|
258
|
+
while (true) {
|
|
259
|
+
const { done, value } = await reader.read();
|
|
260
|
+
if (done) break;
|
|
261
|
+
buffer += decoder.decode(value, { stream: true });
|
|
262
|
+
const lines = buffer.split("\n");
|
|
263
|
+
buffer = lines.pop() ?? "";
|
|
264
|
+
for (const line of lines) {
|
|
265
|
+
const trimmed = line.trim();
|
|
266
|
+
if (trimmed.startsWith("data: ")) {
|
|
267
|
+
const data = trimmed.slice(6);
|
|
268
|
+
if (data === "[DONE]") return;
|
|
269
|
+
try {
|
|
270
|
+
yield JSON.parse(data);
|
|
271
|
+
} catch {
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (buffer.trim().startsWith("data: ")) {
|
|
277
|
+
const data = buffer.trim().slice(6);
|
|
278
|
+
if (data !== "[DONE]") {
|
|
279
|
+
try {
|
|
280
|
+
yield JSON.parse(data);
|
|
281
|
+
} catch {
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
} finally {
|
|
286
|
+
reader.releaseLock();
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
|
|
130
291
|
// src/client/client.ts
|
|
131
292
|
var ContextClient = class {
|
|
132
293
|
apiKey;
|
|
@@ -137,9 +298,17 @@ var ContextClient = class {
|
|
|
137
298
|
*/
|
|
138
299
|
discovery;
|
|
139
300
|
/**
|
|
140
|
-
* Tools resource for executing tools
|
|
301
|
+
* Tools resource for executing tools (pay-per-request)
|
|
141
302
|
*/
|
|
142
303
|
tools;
|
|
304
|
+
/**
|
|
305
|
+
* Query resource for agentic queries (pay-per-response).
|
|
306
|
+
*
|
|
307
|
+
* Unlike `tools.execute()` which calls a single tool once, `query` sends
|
|
308
|
+
* a natural-language question and lets the server handle tool discovery,
|
|
309
|
+
* multi-tool orchestration, self-healing, and AI synthesis — one flat fee.
|
|
310
|
+
*/
|
|
311
|
+
query;
|
|
143
312
|
/**
|
|
144
313
|
* Creates a new Context Protocol client
|
|
145
314
|
*
|
|
@@ -155,6 +324,7 @@ var ContextClient = class {
|
|
|
155
324
|
this.baseUrl = (options.baseUrl ?? "https://ctxprotocol.com").replace(/\/$/, "");
|
|
156
325
|
this.discovery = new Discovery(this);
|
|
157
326
|
this.tools = new Tools(this);
|
|
327
|
+
this.query = new Query(this);
|
|
158
328
|
}
|
|
159
329
|
/**
|
|
160
330
|
* Close the client and clean up resources.
|
|
@@ -240,6 +410,42 @@ var ContextClient = class {
|
|
|
240
410
|
}
|
|
241
411
|
throw lastError ?? new ContextError("Request failed after retries");
|
|
242
412
|
}
|
|
413
|
+
/**
|
|
414
|
+
* Internal method for making authenticated HTTP requests that returns
|
|
415
|
+
* the raw Response object. Used for streaming endpoints (SSE).
|
|
416
|
+
*
|
|
417
|
+
* @internal
|
|
418
|
+
*/
|
|
419
|
+
async _fetchRaw(endpoint, options = {}) {
|
|
420
|
+
if (this._closed) {
|
|
421
|
+
throw new ContextError("Client has been closed");
|
|
422
|
+
}
|
|
423
|
+
const url = `${this.baseUrl}${endpoint}`;
|
|
424
|
+
const response = await fetch(url, {
|
|
425
|
+
...options,
|
|
426
|
+
headers: {
|
|
427
|
+
"Content-Type": "application/json",
|
|
428
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
429
|
+
...options.headers
|
|
430
|
+
}
|
|
431
|
+
});
|
|
432
|
+
if (!response.ok) {
|
|
433
|
+
let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
|
|
434
|
+
let errorCode;
|
|
435
|
+
let helpUrl;
|
|
436
|
+
try {
|
|
437
|
+
const errorBody = await response.json();
|
|
438
|
+
if (errorBody.error) {
|
|
439
|
+
errorMessage = errorBody.error;
|
|
440
|
+
errorCode = errorBody.code;
|
|
441
|
+
helpUrl = errorBody.helpUrl;
|
|
442
|
+
}
|
|
443
|
+
} catch {
|
|
444
|
+
}
|
|
445
|
+
throw new ContextError(errorMessage, errorCode, response.status, helpUrl);
|
|
446
|
+
}
|
|
447
|
+
return response;
|
|
448
|
+
}
|
|
243
449
|
};
|
|
244
450
|
|
|
245
451
|
// src/context/index.ts
|
|
@@ -409,6 +615,7 @@ exports.ContextClient = ContextClient;
|
|
|
409
615
|
exports.ContextError = ContextError;
|
|
410
616
|
exports.Discovery = Discovery;
|
|
411
617
|
exports.META_CONTEXT_REQUIREMENTS_KEY = META_CONTEXT_REQUIREMENTS_KEY;
|
|
618
|
+
exports.Query = Query;
|
|
412
619
|
exports.Tools = Tools;
|
|
413
620
|
exports.createAuthRequired = createAuthRequired;
|
|
414
621
|
exports.createContextMiddleware = createContextMiddleware;
|