diff --git a/.release-please-manifest.json b/.release-please-manifest.json index d0972da..f2ada20 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.7.1" + ".": "1.7.2" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 43f2d50..4fd105c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 1.7.2 (2026-02-20) + +Full Changelog: [v1.7.1...v1.7.2](https://github.com/CASParser/cas-parser-node/compare/v1.7.1...v1.7.2) + +### Bug Fixes + +* **mcp:** initialize SDK lazily to avoid failing the connection on init errors ([2989ad0](https://github.com/CASParser/cas-parser-node/commit/2989ad0e371056cdf52be17d4b18b990533f1514)) + + +### Chores + +* **internal/client:** fix form-urlencoded requests ([f39cb7f](https://github.com/CASParser/cas-parser-node/commit/f39cb7f6c2ad7c20da495ded91c644e432596425)) +* **internal:** allow setting x-stainless-api-key header on mcp server requests ([5b3baf7](https://github.com/CASParser/cas-parser-node/commit/5b3baf7ead67ae4a2e371ceda87d5d9e97019c5d)) +* **internal:** cache fetch instruction calls in MCP server ([335fe62](https://github.com/CASParser/cas-parser-node/commit/335fe623fd4ec8add20d330ab4e85db3165f8e81)) +* **internal:** remove mock server code ([c06dabf](https://github.com/CASParser/cas-parser-node/commit/c06dabff5d1c4bbc99e6691a54646299a1ba74c9)) +* **mcp:** correctly update version in sync with sdk ([0d611f4](https://github.com/CASParser/cas-parser-node/commit/0d611f42d2477e8cbb3e1e746a5f48bc209a3502)) +* update mock server docs ([89099af](https://github.com/CASParser/cas-parser-node/commit/89099af92c2f5dfff6649e325cfe1d1f08fc9d6c)) + ## 1.7.1 (2026-02-14) Full Changelog: [v1.7.0...v1.7.1](https://github.com/CASParser/cas-parser-node/compare/v1.7.0...v1.7.1) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ce6f8cc..c9c4c34 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -65,12 +65,6 @@ $ pnpm link -—global cas-parser-node ## Running tests -Most tests require you to [set up a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests. - -```sh -$ npx prism mock path/to/your/openapi.yml -``` - ```sh $ pnpm run test ``` diff --git a/package.json b/package.json index 74ad47d..8f8f6af 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cas-parser-node", - "version": "1.7.1", + "version": "1.7.2", "description": "The official TypeScript library for the Cas Parser API", "author": "Cas Parser ", "types": "dist/index.d.ts", diff --git a/packages/mcp-server/manifest.json b/packages/mcp-server/manifest.json index fd1110d..da878ae 100644 --- a/packages/mcp-server/manifest.json +++ b/packages/mcp-server/manifest.json @@ -1,7 +1,7 @@ { "dxt_version": "0.2", "name": "cas-parser-node-mcp", - "version": "1.5.1", + "version": "1.7.2", "description": "The official MCP Server for the Cas Parser API", "author": { "name": "Cas Parser", @@ -18,7 +18,9 @@ "entry_point": "index.js", "mcp_config": { "command": "node", - "args": ["${__dirname}/index.js"], + "args": [ + "${__dirname}/index.js" + ], "env": { "CAS_PARSER_API_KEY": "${user_config.CAS_PARSER_API_KEY}" } @@ -39,5 +41,7 @@ "node": ">=18.0.0" } }, - "keywords": ["api"] + "keywords": [ + "api" + ] } diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json index 8c4bc09..5b787e2 100644 --- a/packages/mcp-server/package.json +++ b/packages/mcp-server/package.json @@ -1,6 +1,6 @@ { "name": "cas-parser-node-mcp", - "version": "1.7.1", + "version": "1.7.2", "description": "The official MCP Server for the Cas Parser API", "author": "Cas Parser ", "types": "dist/index.d.ts", diff --git a/packages/mcp-server/src/auth.ts b/packages/mcp-server/src/auth.ts index a867c58..d54a41f 100644 --- a/packages/mcp-server/src/auth.ts +++ b/packages/mcp-server/src/auth.ts @@ -2,9 +2,24 @@ import { IncomingMessage } from 'node:http'; import { ClientOptions } from 'cas-parser-node'; +import { McpOptions } from './options'; -export const parseAuthHeaders = (req: IncomingMessage, required?: boolean): Partial => { +export const parseClientAuthHeaders = (req: IncomingMessage, required?: boolean): Partial => { const apiKey = Array.isArray(req.headers['x-api-key']) ? req.headers['x-api-key'][0] : req.headers['x-api-key']; return { apiKey }; }; + +export const getStainlessApiKey = (req: IncomingMessage, mcpOptions: McpOptions): string | undefined => { + // Try to get the key from the x-stainless-api-key header + const headerKey = + Array.isArray(req.headers['x-stainless-api-key']) ? + req.headers['x-stainless-api-key'][0] + : req.headers['x-stainless-api-key']; + if (headerKey && typeof headerKey === 'string') { + return headerKey; + } + + // Fall back to value set in the mcpOptions (e.g. from environment variable), if provided + return mcpOptions.stainlessApiKey; +}; diff --git a/packages/mcp-server/src/code-tool.ts b/packages/mcp-server/src/code-tool.ts index 0cec16d..0fdea1a 100644 --- a/packages/mcp-server/src/code-tool.ts +++ b/packages/mcp-server/src/code-tool.ts @@ -1,11 +1,17 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { McpTool, Metadata, ToolCallResult, asErrorResult, asTextContentResult } from './types'; +import { + McpRequestContext, + McpTool, + Metadata, + ToolCallResult, + asErrorResult, + asTextContentResult, +} from './types'; import { Tool } from '@modelcontextprotocol/sdk/types.js'; import { readEnv, requireValue } from './util'; import { WorkerInput, WorkerOutput } from './code-tool-types'; import { SdkMethod } from './methods'; -import { CasParser } from 'cas-parser-node'; const prompt = `Runs JavaScript code to interact with the Cas Parser API. @@ -36,7 +42,7 @@ Variables will not persist between calls, so make sure to return or log any data * * @param endpoints - The endpoints to include in the list. */ -export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): McpTool { +export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | undefined }): McpTool { const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] }; const tool: Tool = { name: 'execute', @@ -56,19 +62,24 @@ export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): M required: ['code'], }, }; - const handler = async (client: CasParser, args: any): Promise => { + const handler = async ({ + reqContext, + args, + }: { + reqContext: McpRequestContext; + args: any; + }): Promise => { const code = args.code as string; const intent = args.intent as string | undefined; + const client = reqContext.client; // Do very basic blocking of code that includes forbidden method names. // // WARNING: This is not secure against obfuscation and other evasion methods. If // stronger security blocks are required, then these should be enforced in the downstream // API (e.g., by having users call the MCP server with API keys with limited permissions). - if (params.blockedMethods) { - const blockedMatches = params.blockedMethods.filter((method) => - code.includes(method.fullyQualifiedName), - ); + if (blockedMethods) { + const blockedMatches = blockedMethods.filter((method) => code.includes(method.fullyQualifiedName)); if (blockedMatches.length > 0) { return asErrorResult( `The following methods have been blocked by the MCP server and cannot be used in code execution: ${blockedMatches @@ -78,16 +89,14 @@ export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): M } } - // this is not required, but passing a Stainless API key for the matching project_name - // will allow you to run code-mode queries against non-published versions of your SDK. - const stainlessAPIKey = readEnv('STAINLESS_API_KEY'); const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool'; + // Setting a Stainless API key authenticates requests to the code tool endpoint. const res = await fetch(codeModeEndpoint, { method: 'POST', headers: { - ...(stainlessAPIKey && { Authorization: stainlessAPIKey }), + ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }), 'Content-Type': 'application/json', client_envs: JSON.stringify({ CAS_PARSER_API_KEY: requireValue( diff --git a/packages/mcp-server/src/docs-search-tool.ts b/packages/mcp-server/src/docs-search-tool.ts index 402157c..83e2a27 100644 --- a/packages/mcp-server/src/docs-search-tool.ts +++ b/packages/mcp-server/src/docs-search-tool.ts @@ -1,8 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { Metadata, asTextContentResult } from './types'; -import { readEnv } from './util'; - +import { Metadata, McpRequestContext, asTextContentResult } from './types'; import { Tool } from '@modelcontextprotocol/sdk/types.js'; export const metadata: Metadata = { @@ -43,13 +41,18 @@ export const tool: Tool = { const docsSearchURL = process.env['DOCS_SEARCH_URL'] || 'https://api.stainless.com/api/projects/cas-parser/docs/search'; -export const handler = async (_: unknown, args: Record | undefined) => { +export const handler = async ({ + reqContext, + args, +}: { + reqContext: McpRequestContext; + args: Record | undefined; +}) => { const body = args as any; const query = new URLSearchParams(body).toString(); - const stainlessAPIKey = readEnv('STAINLESS_API_KEY'); const result = await fetch(`${docsSearchURL}?${query}`, { headers: { - ...(stainlessAPIKey && { Authorization: stainlessAPIKey }), + ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }), }, }); diff --git a/packages/mcp-server/src/http.ts b/packages/mcp-server/src/http.ts index d808262..03a0102 100644 --- a/packages/mcp-server/src/http.ts +++ b/packages/mcp-server/src/http.ts @@ -6,7 +6,7 @@ import { ClientOptions } from 'cas-parser-node'; import express from 'express'; import morgan from 'morgan'; import morganBody from 'morgan-body'; -import { parseAuthHeaders } from './auth'; +import { getStainlessApiKey, parseClientAuthHeaders } from './auth'; import { McpOptions } from './options'; import { initMcpServer, newMcpServer } from './server'; @@ -21,28 +21,20 @@ const newServer = async ({ req: express.Request; res: express.Response; }): Promise => { - const server = await newMcpServer(); + const stainlessApiKey = getStainlessApiKey(req, mcpOptions); + const server = await newMcpServer(stainlessApiKey); - try { - const authOptions = parseAuthHeaders(req, false); - await initMcpServer({ - server: server, - mcpOptions: mcpOptions, - clientOptions: { - ...clientOptions, - ...authOptions, - }, - }); - } catch (error) { - res.status(401).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: `Unauthorized: ${error instanceof Error ? error.message : error}`, - }, - }); - return null; - } + const authOptions = parseClientAuthHeaders(req, false); + + await initMcpServer({ + server: server, + mcpOptions: mcpOptions, + clientOptions: { + ...clientOptions, + ...authOptions, + }, + stainlessApiKey: stainlessApiKey, + }); return server; }; @@ -112,13 +104,17 @@ export const streamableHTTPApp = ({ return app; }; -export const launchStreamableHTTPServer = async (params: { +export const launchStreamableHTTPServer = async ({ + mcpOptions, + debug, + port, +}: { mcpOptions: McpOptions; debug: boolean; port: number | string | undefined; }) => { - const app = streamableHTTPApp({ mcpOptions: params.mcpOptions, debug: params.debug }); - const server = app.listen(params.port); + const app = streamableHTTPApp({ mcpOptions, debug }); + const server = app.listen(port); const address = server.address(); if (typeof address === 'string') { @@ -126,6 +122,6 @@ export const launchStreamableHTTPServer = async (params: { } else if (address !== null) { console.error(`MCP Server running on streamable HTTP on port ${address.port}`); } else { - console.error(`MCP Server running on streamable HTTP on port ${params.port}`); + console.error(`MCP Server running on streamable HTTP on port ${port}`); } }; diff --git a/packages/mcp-server/src/index.ts b/packages/mcp-server/src/index.ts index 003a765..654d25c 100644 --- a/packages/mcp-server/src/index.ts +++ b/packages/mcp-server/src/index.ts @@ -24,7 +24,7 @@ async function main() { await launchStreamableHTTPServer({ mcpOptions: options, debug: options.debug, - port: options.port ?? options.socket, + port: options.socket ?? options.port, }); break; } diff --git a/packages/mcp-server/src/instructions.ts b/packages/mcp-server/src/instructions.ts new file mode 100644 index 0000000..1a2b4ee --- /dev/null +++ b/packages/mcp-server/src/instructions.ts @@ -0,0 +1,74 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { readEnv } from './util'; + +const INSTRUCTIONS_CACHE_TTL_MS = 15 * 60 * 1000; // 15 minutes + +interface InstructionsCacheEntry { + fetchedInstructions: string; + fetchedAt: number; +} + +const instructionsCache = new Map(); + +// Periodically evict stale entries so the cache doesn't grow unboundedly. +const _cacheCleanupInterval = setInterval(() => { + const now = Date.now(); + for (const [key, entry] of instructionsCache) { + if (now - entry.fetchedAt > INSTRUCTIONS_CACHE_TTL_MS) { + instructionsCache.delete(key); + } + } +}, INSTRUCTIONS_CACHE_TTL_MS); + +// Don't keep the process alive just for cleanup. +_cacheCleanupInterval.unref(); + +export async function getInstructions(stainlessApiKey: string | undefined): Promise { + const cacheKey = stainlessApiKey ?? ''; + const cached = instructionsCache.get(cacheKey); + + if (cached && Date.now() - cached.fetchedAt <= INSTRUCTIONS_CACHE_TTL_MS) { + return cached.fetchedInstructions; + } + + const fetchedInstructions = await fetchLatestInstructions(stainlessApiKey); + instructionsCache.set(cacheKey, { fetchedInstructions, fetchedAt: Date.now() }); + return fetchedInstructions; +} + +async function fetchLatestInstructions(stainlessApiKey: string | undefined): Promise { + // Setting the stainless API key is optional, but may be required + // to authenticate requests to the Stainless API. + const response = await fetch( + readEnv('CODE_MODE_INSTRUCTIONS_URL') ?? 'https://api.stainless.com/api/ai/instructions/cas-parser', + { + method: 'GET', + headers: { ...(stainlessApiKey && { Authorization: stainlessApiKey }) }, + }, + ); + + let instructions: string | undefined; + if (!response.ok) { + console.warn( + 'Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...', + ); + + instructions = ` + This is the cas-parser MCP server. You will use Code Mode to help the user perform + actions. You can use search_docs tool to learn about how to take action with this server. Then, + you will write TypeScript code using the execute tool take action. It is CRITICAL that you be + thoughtful and deliberate when executing code. Always try to entirely solve the problem in code + block: it can be as long as you need to get the job done! + `; + } + + instructions ??= ((await response.json()) as { instructions: string }).instructions; + instructions = ` + If needed, you can get the current time by executing Date.now(). + + ${instructions} + `; + + return instructions; +} diff --git a/packages/mcp-server/src/options.ts b/packages/mcp-server/src/options.ts index cfde21d..32a8871 100644 --- a/packages/mcp-server/src/options.ts +++ b/packages/mcp-server/src/options.ts @@ -4,6 +4,7 @@ import qs from 'qs'; import yargs from 'yargs'; import { hideBin } from 'yargs/helpers'; import z from 'zod'; +import { readEnv } from './util'; export type CLIOptions = McpOptions & { debug: boolean; @@ -14,6 +15,7 @@ export type CLIOptions = McpOptions & { export type McpOptions = { includeDocsTools?: boolean | undefined; + stainlessApiKey?: string | undefined; codeAllowHttpGets?: boolean | undefined; codeAllowedMethods?: string[] | undefined; codeBlockedMethods?: string[] | undefined; @@ -51,6 +53,12 @@ export function parseCLIOptions(): CLIOptions { description: 'Port to serve on if using http transport', }) .option('socket', { type: 'string', description: 'Unix socket to serve on if using http transport' }) + .option('stainless-api-key', { + type: 'string', + default: readEnv('STAINLESS_API_KEY'), + description: + 'API key for Stainless. Used to authenticate requests to Stainless-hosted tools endpoints.', + }) .option('tools', { type: 'string', array: true, @@ -81,6 +89,7 @@ export function parseCLIOptions(): CLIOptions { return { ...(includeDocsTools !== undefined && { includeDocsTools }), debug: !!argv.debug, + stainlessApiKey: argv.stainlessApiKey, codeAllowHttpGets: argv.codeAllowHttpGets, codeAllowedMethods: argv.codeAllowedMethods, codeBlockedMethods: argv.codeBlockedMethods, diff --git a/packages/mcp-server/src/server.ts b/packages/mcp-server/src/server.ts index 96b573c..9112f69 100644 --- a/packages/mcp-server/src/server.ts +++ b/packages/mcp-server/src/server.ts @@ -11,55 +11,20 @@ import { ClientOptions } from 'cas-parser-node'; import CasParser from 'cas-parser-node'; import { codeTool } from './code-tool'; import docsSearchTool from './docs-search-tool'; +import { getInstructions } from './instructions'; import { McpOptions } from './options'; import { blockedMethodsForCodeTool } from './methods'; -import { HandlerFunction, McpTool } from './types'; +import { HandlerFunction, McpRequestContext, ToolCallResult, McpTool } from './types'; import { readEnv } from './util'; -async function getInstructions() { - // This API key is optional; providing it allows the server to fetch instructions for unreleased versions. - const stainlessAPIKey = readEnv('STAINLESS_API_KEY'); - const response = await fetch( - readEnv('CODE_MODE_INSTRUCTIONS_URL') ?? 'https://api.stainless.com/api/ai/instructions/cas-parser', - { - method: 'GET', - headers: { ...(stainlessAPIKey && { Authorization: stainlessAPIKey }) }, - }, - ); - - let instructions: string | undefined; - if (!response.ok) { - console.warn( - 'Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...', - ); - - instructions = ` - This is the cas-parser MCP server. You will use Code Mode to help the user perform - actions. You can use search_docs tool to learn about how to take action with this server. Then, - you will write TypeScript code using the execute tool take action. It is CRITICAL that you be - thoughtful and deliberate when executing code. Always try to entirely solve the problem in code - block: it can be as long as you need to get the job done! - `; - } - - instructions ??= ((await response.json()) as { instructions: string }).instructions; - instructions = ` - The current time in Unix timestamps is ${Date.now()}. - - ${instructions} - `; - - return instructions; -} - -export const newMcpServer = async () => +export const newMcpServer = async (stainlessApiKey: string | undefined) => new McpServer( { name: 'cas_parser_node_api', - version: '1.7.1', + version: '1.7.2', }, { - instructions: await getInstructions(), + instructions: await getInstructions(stainlessApiKey), capabilities: { tools: {}, logging: {} }, }, ); @@ -72,6 +37,7 @@ export async function initMcpServer(params: { server: Server | McpServer; clientOptions?: ClientOptions; mcpOptions?: McpOptions; + stainlessApiKey?: string | undefined; }) { const server = params.server instanceof McpServer ? params.server.server : params.server; @@ -90,15 +56,33 @@ export async function initMcpServer(params: { error: logAtLevel('error'), }; - let client = new CasParser({ - ...{ environment: (readEnv('CAS_PARSER_ENVIRONMENT') || undefined) as any }, - logger, - ...params.clientOptions, - defaultHeaders: { - ...params.clientOptions?.defaultHeaders, - 'X-Stainless-MCP': 'true', - }, - }); + let _client: CasParser | undefined; + let _clientError: Error | undefined; + let _logLevel: 'debug' | 'info' | 'warn' | 'error' | 'off' | undefined; + + const getClient = (): CasParser => { + if (_clientError) throw _clientError; + if (!_client) { + try { + _client = new CasParser({ + ...{ environment: (readEnv('CAS_PARSER_ENVIRONMENT') || undefined) as any }, + logger, + ...params.clientOptions, + defaultHeaders: { + ...params.clientOptions?.defaultHeaders, + 'X-Stainless-MCP': 'true', + }, + }); + if (_logLevel) { + _client = _client.withOptions({ logLevel: _logLevel }); + } + } catch (e) { + _clientError = e instanceof Error ? e : new Error(String(e)); + throw _clientError; + } + } + return _client; + }; const providedTools = selectTools(params.mcpOptions); const toolMap = Object.fromEntries(providedTools.map((mcpTool) => [mcpTool.tool.name, mcpTool])); @@ -116,29 +100,56 @@ export async function initMcpServer(params: { throw new Error(`Unknown tool: ${name}`); } - return executeHandler(mcpTool.handler, client, args); + let client: CasParser; + try { + client = getClient(); + } catch (error) { + return { + content: [ + { + type: 'text' as const, + text: `Failed to initialize client: ${error instanceof Error ? error.message : String(error)}`, + }, + ], + isError: true, + }; + } + + return executeHandler({ + handler: mcpTool.handler, + reqContext: { + client, + stainlessApiKey: params.stainlessApiKey ?? params.mcpOptions?.stainlessApiKey, + }, + args, + }); }); server.setRequestHandler(SetLevelRequestSchema, async (request) => { const { level } = request.params; + let logLevel: 'debug' | 'info' | 'warn' | 'error' | 'off'; switch (level) { case 'debug': - client = client.withOptions({ logLevel: 'debug' }); + logLevel = 'debug'; break; case 'info': - client = client.withOptions({ logLevel: 'info' }); + logLevel = 'info'; break; case 'notice': case 'warning': - client = client.withOptions({ logLevel: 'warn' }); + logLevel = 'warn'; break; case 'error': - client = client.withOptions({ logLevel: 'error' }); + logLevel = 'error'; break; default: - client = client.withOptions({ logLevel: 'off' }); + logLevel = 'off'; break; } + _logLevel = logLevel; + if (_client) { + _client = _client.withOptions({ logLevel }); + } return {}; }); } @@ -161,10 +172,14 @@ export function selectTools(options?: McpOptions): McpTool[] { /** * Runs the provided handler with the given client and arguments. */ -export async function executeHandler( - handler: HandlerFunction, - client: CasParser, - args: Record | undefined, -) { - return await handler(client, args || {}); +export async function executeHandler({ + handler, + reqContext, + args, +}: { + handler: HandlerFunction; + reqContext: McpRequestContext; + args: Record | undefined; +}): Promise { + return await handler({ reqContext, args: args || {} }); } diff --git a/packages/mcp-server/src/stdio.ts b/packages/mcp-server/src/stdio.ts index 57b9912..ceccaed 100644 --- a/packages/mcp-server/src/stdio.ts +++ b/packages/mcp-server/src/stdio.ts @@ -3,9 +3,9 @@ import { McpOptions } from './options'; import { initMcpServer, newMcpServer } from './server'; export const launchStdioServer = async (mcpOptions: McpOptions) => { - const server = await newMcpServer(); + const server = await newMcpServer(mcpOptions.stainlessApiKey); - await initMcpServer({ server, mcpOptions }); + await initMcpServer({ server, mcpOptions, stainlessApiKey: mcpOptions.stainlessApiKey }); const transport = new StdioServerTransport(); await server.connect(transport); diff --git a/packages/mcp-server/src/types.ts b/packages/mcp-server/src/types.ts index 36dd727..5b8e8a4 100644 --- a/packages/mcp-server/src/types.ts +++ b/packages/mcp-server/src/types.ts @@ -42,10 +42,18 @@ export type ToolCallResult = { isError?: boolean; }; -export type HandlerFunction = ( - client: CasParser, - args: Record | undefined, -) => Promise; +export type McpRequestContext = { + client: CasParser; + stainlessApiKey?: string | undefined; +}; + +export type HandlerFunction = ({ + reqContext, + args, +}: { + reqContext: McpRequestContext; + args: Record | undefined; +}) => Promise; export function asTextContentResult(result: unknown): ToolCallResult { return { diff --git a/release-please-config.json b/release-please-config.json index c45c17b..363e246 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -67,6 +67,11 @@ "type": "json", "path": "packages/mcp-server/package.json", "jsonpath": "$.version" + }, + { + "type": "json", + "path": "packages/mcp-server/manifest.json", + "jsonpath": "$.version" } ] } diff --git a/scripts/mock b/scripts/mock deleted file mode 100755 index 0b28f6e..0000000 --- a/scripts/mock +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env bash - -set -e - -cd "$(dirname "$0")/.." - -if [[ -n "$1" && "$1" != '--'* ]]; then - URL="$1" - shift -else - URL="$(grep 'openapi_spec_url' .stats.yml | cut -d' ' -f2)" -fi - -# Check if the URL is empty -if [ -z "$URL" ]; then - echo "Error: No OpenAPI spec path/url provided or found in .stats.yml" - exit 1 -fi - -echo "==> Starting mock server with URL ${URL}" - -# Run prism mock on the given spec -if [ "$1" == "--daemon" ]; then - npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" &> .prism.log & - - # Wait for server to come online - echo -n "Waiting for server" - while ! grep -q "✖ fatal\|Prism is listening" ".prism.log" ; do - echo -n "." - sleep 0.1 - done - - if grep -q "✖ fatal" ".prism.log"; then - cat .prism.log - exit 1 - fi - - echo -else - npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" -fi diff --git a/scripts/test b/scripts/test index 7bce051..548da9b 100755 --- a/scripts/test +++ b/scripts/test @@ -4,53 +4,7 @@ set -e cd "$(dirname "$0")/.." -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[0;33m' -NC='\033[0m' # No Color -function prism_is_running() { - curl --silent "http://localhost:4010" >/dev/null 2>&1 -} - -kill_server_on_port() { - pids=$(lsof -t -i tcp:"$1" || echo "") - if [ "$pids" != "" ]; then - kill "$pids" - echo "Stopped $pids." - fi -} - -function is_overriding_api_base_url() { - [ -n "$TEST_API_BASE_URL" ] -} - -if ! is_overriding_api_base_url && ! prism_is_running ; then - # When we exit this script, make sure to kill the background mock server process - trap 'kill_server_on_port 4010' EXIT - - # Start the dev server - ./scripts/mock --daemon -fi - -if is_overriding_api_base_url ; then - echo -e "${GREEN}✔ Running tests against ${TEST_API_BASE_URL}${NC}" - echo -elif ! prism_is_running ; then - echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Prism server" - echo -e "running against your OpenAPI spec." - echo - echo -e "To run the server, pass in the path or url of your OpenAPI" - echo -e "spec to the prism command:" - echo - echo -e " \$ ${YELLOW}npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock path/to/your.openapi.yml${NC}" - echo - - exit 1 -else - echo -e "${GREEN}✔ Mock prism server is running with your OpenAPI spec${NC}" - echo -fi echo "==> Running tests" ./node_modules/.bin/jest "$@" diff --git a/src/client.ts b/src/client.ts index 1bad16f..bc8fec0 100644 --- a/src/client.ts +++ b/src/client.ts @@ -757,6 +757,14 @@ export class CasParser { (Symbol.iterator in body && 'next' in body && typeof body.next === 'function')) ) { return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body as AsyncIterable) }; + } else if ( + typeof body === 'object' && + headers.values.get('content-type') === 'application/x-www-form-urlencoded' + ) { + return { + bodyHeaders: { 'content-type': 'application/x-www-form-urlencoded' }, + body: this.stringifyQuery(body as Record), + }; } else { return this.#encoder({ body, headers }); } diff --git a/src/version.ts b/src/version.ts index 63fe850..c742ace 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = '1.7.1'; // x-release-please-version +export const VERSION = '1.7.2'; // x-release-please-version diff --git a/tests/api-resources/access-token.test.ts b/tests/api-resources/access-token.test.ts index 55ca752..6559771 100644 --- a/tests/api-resources/access-token.test.ts +++ b/tests/api-resources/access-token.test.ts @@ -8,7 +8,7 @@ const client = new CasParser({ }); describe('resource accessToken', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('create', async () => { const responsePromise = client.accessToken.create(); const rawResponse = await responsePromise.asResponse(); @@ -20,7 +20,7 @@ describe('resource accessToken', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: request options and params are passed correctly', async () => { // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error await expect( diff --git a/tests/api-resources/cams-kfintech.test.ts b/tests/api-resources/cams-kfintech.test.ts index 71a0d43..97892f3 100644 --- a/tests/api-resources/cams-kfintech.test.ts +++ b/tests/api-resources/cams-kfintech.test.ts @@ -8,7 +8,7 @@ const client = new CasParser({ }); describe('resource camsKfintech', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('parse', async () => { const responsePromise = client.camsKfintech.parse({}); const rawResponse = await responsePromise.asResponse(); diff --git a/tests/api-resources/cdsl/cdsl.test.ts b/tests/api-resources/cdsl/cdsl.test.ts index 47e8f17..4a6fec1 100644 --- a/tests/api-resources/cdsl/cdsl.test.ts +++ b/tests/api-resources/cdsl/cdsl.test.ts @@ -8,7 +8,7 @@ const client = new CasParser({ }); describe('resource cdsl', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('parsePdf', async () => { const responsePromise = client.cdsl.parsePdf({}); const rawResponse = await responsePromise.asResponse(); diff --git a/tests/api-resources/cdsl/fetch.test.ts b/tests/api-resources/cdsl/fetch.test.ts index a41c723..ac92491 100644 --- a/tests/api-resources/cdsl/fetch.test.ts +++ b/tests/api-resources/cdsl/fetch.test.ts @@ -8,7 +8,7 @@ const client = new CasParser({ }); describe('resource fetch', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('requestOtp: only required params', async () => { const responsePromise = client.cdsl.fetch.requestOtp({ bo_id: '1234567890123456', @@ -24,7 +24,7 @@ describe('resource fetch', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('requestOtp: required and optional params', async () => { const response = await client.cdsl.fetch.requestOtp({ bo_id: '1234567890123456', @@ -33,7 +33,7 @@ describe('resource fetch', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('verifyOtp: only required params', async () => { const responsePromise = client.cdsl.fetch.verifyOtp('session_id', { otp: '123456' }); const rawResponse = await responsePromise.asResponse(); @@ -45,7 +45,7 @@ describe('resource fetch', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('verifyOtp: required and optional params', async () => { const response = await client.cdsl.fetch.verifyOtp('session_id', { otp: '123456', num_periods: 6 }); }); diff --git a/tests/api-resources/contract-note.test.ts b/tests/api-resources/contract-note.test.ts index 3327a12..c3dd0d9 100644 --- a/tests/api-resources/contract-note.test.ts +++ b/tests/api-resources/contract-note.test.ts @@ -8,7 +8,7 @@ const client = new CasParser({ }); describe('resource contractNote', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('parse', async () => { const responsePromise = client.contractNote.parse({}); const rawResponse = await responsePromise.asResponse(); diff --git a/tests/api-resources/credits.test.ts b/tests/api-resources/credits.test.ts index 1090755..3567262 100644 --- a/tests/api-resources/credits.test.ts +++ b/tests/api-resources/credits.test.ts @@ -8,7 +8,7 @@ const client = new CasParser({ }); describe('resource credits', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('check', async () => { const responsePromise = client.credits.check(); const rawResponse = await responsePromise.asResponse(); diff --git a/tests/api-resources/inbox.test.ts b/tests/api-resources/inbox.test.ts index 605455c..bd494a2 100644 --- a/tests/api-resources/inbox.test.ts +++ b/tests/api-resources/inbox.test.ts @@ -8,7 +8,7 @@ const client = new CasParser({ }); describe('resource inbox', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('checkConnectionStatus: only required params', async () => { const responsePromise = client.inbox.checkConnectionStatus({ 'x-inbox-token': 'x-inbox-token' }); const rawResponse = await responsePromise.asResponse(); @@ -20,12 +20,12 @@ describe('resource inbox', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('checkConnectionStatus: required and optional params', async () => { const response = await client.inbox.checkConnectionStatus({ 'x-inbox-token': 'x-inbox-token' }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('connectEmail: only required params', async () => { const responsePromise = client.inbox.connectEmail({ redirect_uri: 'https://yourapp.com/oauth-callback' }); const rawResponse = await responsePromise.asResponse(); @@ -37,7 +37,7 @@ describe('resource inbox', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('connectEmail: required and optional params', async () => { const response = await client.inbox.connectEmail({ redirect_uri: 'https://yourapp.com/oauth-callback', @@ -45,7 +45,7 @@ describe('resource inbox', () => { }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('disconnectEmail: only required params', async () => { const responsePromise = client.inbox.disconnectEmail({ 'x-inbox-token': 'x-inbox-token' }); const rawResponse = await responsePromise.asResponse(); @@ -57,12 +57,12 @@ describe('resource inbox', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('disconnectEmail: required and optional params', async () => { const response = await client.inbox.disconnectEmail({ 'x-inbox-token': 'x-inbox-token' }); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('listCasFiles: only required params', async () => { const responsePromise = client.inbox.listCasFiles({ 'x-inbox-token': 'x-inbox-token' }); const rawResponse = await responsePromise.asResponse(); @@ -74,7 +74,7 @@ describe('resource inbox', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('listCasFiles: required and optional params', async () => { const response = await client.inbox.listCasFiles({ 'x-inbox-token': 'x-inbox-token', diff --git a/tests/api-resources/kfintech.test.ts b/tests/api-resources/kfintech.test.ts index 3b7e247..f4ce5d8 100644 --- a/tests/api-resources/kfintech.test.ts +++ b/tests/api-resources/kfintech.test.ts @@ -8,7 +8,7 @@ const client = new CasParser({ }); describe('resource kfintech', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('generateCas: only required params', async () => { const responsePromise = client.kfintech.generateCas({ email: 'user@example.com', @@ -25,7 +25,7 @@ describe('resource kfintech', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('generateCas: required and optional params', async () => { const response = await client.kfintech.generateCas({ email: 'user@example.com', diff --git a/tests/api-resources/logs.test.ts b/tests/api-resources/logs.test.ts index 0e8c0fc..2d1b99a 100644 --- a/tests/api-resources/logs.test.ts +++ b/tests/api-resources/logs.test.ts @@ -8,7 +8,7 @@ const client = new CasParser({ }); describe('resource logs', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('create', async () => { const responsePromise = client.logs.create(); const rawResponse = await responsePromise.asResponse(); @@ -20,7 +20,7 @@ describe('resource logs', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('create: request options and params are passed correctly', async () => { // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error await expect( @@ -35,7 +35,7 @@ describe('resource logs', () => { ).rejects.toThrow(CasParser.NotFoundError); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('getSummary', async () => { const responsePromise = client.logs.getSummary(); const rawResponse = await responsePromise.asResponse(); @@ -47,7 +47,7 @@ describe('resource logs', () => { expect(dataAndResponse.response).toBe(rawResponse); }); - // Prism tests are disabled + // Mock server tests are disabled test.skip('getSummary: request options and params are passed correctly', async () => { // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error await expect( diff --git a/tests/api-resources/nsdl.test.ts b/tests/api-resources/nsdl.test.ts index 2016e03..745ef2f 100644 --- a/tests/api-resources/nsdl.test.ts +++ b/tests/api-resources/nsdl.test.ts @@ -8,7 +8,7 @@ const client = new CasParser({ }); describe('resource nsdl', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('parse', async () => { const responsePromise = client.nsdl.parse({}); const rawResponse = await responsePromise.asResponse(); diff --git a/tests/api-resources/smart.test.ts b/tests/api-resources/smart.test.ts index 3abfd73..883bfca 100644 --- a/tests/api-resources/smart.test.ts +++ b/tests/api-resources/smart.test.ts @@ -8,7 +8,7 @@ const client = new CasParser({ }); describe('resource smart', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('parseCasPdf', async () => { const responsePromise = client.smart.parseCasPdf({}); const rawResponse = await responsePromise.asResponse(); diff --git a/tests/api-resources/verify-token.test.ts b/tests/api-resources/verify-token.test.ts index 5c8bef4..75827c6 100644 --- a/tests/api-resources/verify-token.test.ts +++ b/tests/api-resources/verify-token.test.ts @@ -8,7 +8,7 @@ const client = new CasParser({ }); describe('resource verifyToken', () => { - // Prism tests are disabled + // Mock server tests are disabled test.skip('verify', async () => { const responsePromise = client.verifyToken.verify(); const rawResponse = await responsePromise.asResponse();