import { Tool } from "@modelcontextprotocol/sdk/types.js"; import type { Agent as HttpsAgent } from "node:https"; import { AuthProvider } from "./auth-provider.js"; import { OpenAPISpecLoader } from "./openapi-loader.js"; import { OpenAPIV3 } from "openapi-types"; /** * Client for making API calls to the backend service */ export declare class ApiClient { private axiosInstance; private toolsMap; private authProvider; private specLoader?; private openApiSpec?; private excludeTagsLower; /** * Create a new API client * * @param baseUrl - Base URL for the API * @param authProviderOrHeaders - AuthProvider instance or static headers for backward compatibility * @param specLoader - Optional OpenAPI spec loader for dynamic meta-tools * @param options - Optional HTTP client configuration */ constructor(baseUrl: string, authProviderOrHeaders?: AuthProvider | Record, specLoader?: OpenAPISpecLoader, options?: ApiClientOptions); private operationHasExcludedTag; /** * Set the available tools for the client * * @param tools - Map of tool ID to tool definition */ setTools(tools: Map): void; /** * Set the OpenAPI specification for dynamic meta-tools * * @param spec - The OpenAPI specification document */ setOpenApiSpec(spec: OpenAPIV3.Document): void; /** * Get a tool definition by ID * * @param toolId - The tool ID * @returns The tool definition if found */ private getToolDefinition; private resolveRequestBodyObject; /** * Check whether a path item has a (valid HTTP) operation, optionally for a specific method */ private pathItemHasOperation; /** * Resolve an endpoint supplied to a dynamic meta-tool to a path in the OpenAPI spec. * * Accepts either a spec path template (`/users/{id}`) or a concrete path * (`/users/123`). Concrete paths are matched against the spec's path templates and the * path parameter values are extracted. Literal paths win over templates, and among * templates the most specific one (fewest parameters, most literal characters) wins. * * @param endpoint - The endpoint path supplied by the caller * @param method - Optional HTTP method the resolved path must support * Segments of the endpoint that are themselves placeholders (e.g. a partially filled * `/users/123/posts/{postId}`) are not treated as values; they are reported in * `placeholderNames` (template name -> name used by the caller) so the value can be * taken from the caller's params. * * @returns The matched spec path, its path item and the extracted path parameters */ private resolveEndpoint; /** * Interpolate `{param}` placeholders in a spec path template using the given params. * Consumed params are removed from the returned params object. */ private interpolatePathParams; /** * Build the params for a request to a resolved endpoint: query string from the * endpoint, then caller params, then path values extracted from a concrete endpoint. * * Query string values may fill path placeholders; any that remain are sent as query * parameters for every method (see `makeDirectHttpRequest`). */ private buildEndpointParams; private getRequestBodyInfo; /** * How a dynamic-mode caller must pass the request body of an operation (see {@link BodyEncoding}). */ private getSpecBodyEncoding; /** * Build a binary request body (Issue #105): the payload is passed base64-encoded in the * wrapper argument and sent as raw bytes with the declared Content-Type. * * @param params - Tool arguments left over after path/query/header extraction * @param wrapperKey - Name of the argument that carries the base64 payload * @param contentType - Content-Type declared by the OpenAPI spec (if any) */ private buildBinaryRequestBody; /** * Execute a request, reading the body as raw bytes and decoding it by Content-Type. * Binary payloads are returned as {@link BinaryResponse} instead of a corrupted string. */ private sendRequest; private getHeader; /** * URI identifying a binary response for MCP embedded resources. * Uses only the request path: the upstream host, credentials in the base URL * and query string are never exposed to the MCP client. */ private getResponseUri; /** * Error responses are also read as raw bytes; decode them so error messages and * AuthProvider.handleAuthError() see text/JSON rather than a Buffer. */ private decodeErrorResponse; /** * Execute an API call based on the tool ID and parameters * * @param toolId - The tool ID in format METHOD-path-parts * @param params - Parameters for the API call * @returns The API response data */ executeApiCall(toolId: string, params: Record): Promise; /** * Execute an API call with optional retry on auth error * * @param toolId - The tool ID in format METHOD-path-parts * @param params - Parameters for the API call * @param isRetry - Whether this is a retry attempt * @returns The API response data */ private executeApiCallWithRetry; /** * Build the request body from the remaining (non path/query/header) arguments, * reversing the renames applied when the tool input schema was generated (Issue #102): * - a non-object body exposed as a `body` wrapper property is sent as the bare value * - body properties prefixed with `body_` due to a name collision get their original name * * @param inputSchema - The tool's input schema (may carry x-body-* metadata) * @param params - Remaining arguments after extracting path/query/header parameters * @returns The request body to send */ private buildRequestBody; /** * Parse a tool ID into HTTP method and path * * @param toolId - Tool ID in format METHOD::pathPart * @returns Object containing method and path */ private parseToolId; /** * Process query parameters for GET requests * Converts arrays to comma-separated strings * * @param params - The original parameters * @returns Processed parameters */ private processQueryParams; /** * Sanitize error data to prevent information disclosure * Redacts sensitive data from authentication errors and truncates large responses * * @param data - The error response data * @param statusCode - The HTTP status code * @returns Sanitized error data string */ private sanitizeErrorData; /** * Handle the LIST-API-ENDPOINTS meta-tool * Returns a list of all available API endpoints from the loaded tools */ private handleListApiEndpoints; /** * Handle the GET-API-ENDPOINT-SCHEMA meta-tool * Returns the JSON schema for a specified API endpoint */ private handleGetApiEndpointSchema; /** * Keys whose value came from the endpoint's query string (not overridden by explicit * params or path values), so they stay in the query string for body methods. */ private endpointQueryKeys; /** * Handle the INVOKE-API-ENDPOINT meta-tool * Dynamically invokes an API endpoint with the provided parameters */ private handleInvokeApiEndpoint; /** * Make a direct HTTP request without going through the tool system * Used by dynamic meta-tools when we have OpenAPI spec but no corresponding tool * * @param method - HTTP method * @param path - Spec path template; `{param}` placeholders are filled from params * @param params - Request parameters; path parameters are consumed, the rest go to * the query string (GET-like) or request body * @param queryKeys - Keys that came from the endpoint's query string; these always go * to the query string, also for body methods */ private makeDirectHttpRequest; } export interface ApiClientOptions { excludeTags?: string[]; httpsAgent?: HttpsAgent; }