Skip to main content
Glama

api_call

Execute HTTP requests to REST APIs by specifying method, path, parameters, headers, and body data for testing and integration.

Instructions

调用示例API API的通用工具。支持所有HTTP方法和路径。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
bodyNo请求体数据(用于POST/PUT等方法)
headersNo请求头,例如: {"Authorization": "Bearer token"}
methodYesHTTP方法
pathYesAPI路径,例如: /users/{id} 或 /posts
pathParamsNo路径参数,例如: {"id": "123"}
queryParamsNo查询参数,例如: {"limit": 10, "offset": 0}

Implementation Reference

  • The primary handler function for the 'api_call' tool. It constructs and executes HTTP requests based on provided method, path, parameters, headers, and body. Includes retry logic, timeout handling, and response parsing.
    async function executeUnifiedApiCall(args) { const { method, path, pathParams = {}, queryParams = {}, headers = {}, body, } = args; if (!method || !path) { throw new McpError(ErrorCode.InvalidParams, "method和path参数是必需的"); } let lastError; for (let attempt = 1; attempt <= config.http.maxRetries; attempt++) { try { const { url, headers: requestHeaders, body: requestBody, } = buildUnifiedApiRequest( method, path, pathParams, queryParams, headers, body ); if (config.logging.enableConsole) { console.error(`🚀 发起API调用: ${method.toUpperCase()} ${url}`); } const controller = new AbortController(); const timeoutId = setTimeout( () => controller.abort(), config.http.timeout ); try { const response = await fetch(url, { method: method.toUpperCase(), headers: requestHeaders, body: requestBody, signal: controller.signal, }); clearTimeout(timeoutId); const contentType = response.headers.get("content-type"); let responseData; if (contentType && contentType.includes("application/json")) { responseData = await response.json(); } else { responseData = await response.text(); } if (config.logging.enableConsole) { console.error( `✅ API调用成功: ${response.status} ${response.statusText}` ); } return { content: [ { type: "text", text: `状态码: ${response.status} ${ response.statusText }\n内容类型: ${ contentType || "unknown" }\n响应数据: ${JSON.stringify(responseData, null, 2)}`, }, ], }; } catch (fetchError) { clearTimeout(timeoutId); if (fetchError.name === "AbortError") { throw new Error(`请求超时 (${config.http.timeout}ms)`); } throw fetchError; } } catch (error) { lastError = error; if (config.logging.enableConsole) { console.error( `🔄 API调用失败 (尝试 ${attempt}/${config.http.maxRetries}):`, error.message ); } if (attempt === config.http.maxRetries || error instanceof McpError) { break; } await delay(config.http.retryDelay * attempt); } } if (lastError instanceof McpError) { throw lastError; } throw new McpError( ErrorCode.InternalError, `API调用失败: ${lastError.message}` ); }
  • Input schema definition for the 'api_call' tool, specifying required fields like method and path, and optional parameters for pathParams, queryParams, headers, and body.
    inputSchema: { type: "object", properties: { method: { type: "string", enum: ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"], description: "HTTP方法", }, path: { type: "string", description: "API路径,例如: /users/{id} 或 /posts", }, pathParams: { type: "object", description: '路径参数,例如: {"id": "123"}', additionalProperties: true, }, queryParams: { type: "object", description: '查询参数,例如: {"limit": 10, "offset": 0}', additionalProperties: true, }, headers: { type: "object", description: '请求头,例如: {"Authorization": "Bearer token"}', additionalProperties: true, }, body: { type: "object", description: "请求体数据(用于POST/PUT等方法)", additionalProperties: true, }, }, required: ["method", "path"], },
  • src/index.js:824-829 (registration)
    Registration via the ListToolsRequestSchema handler, which dynamically generates and returns the list of tools including 'api_call' from createUnifiedApiTools().
    server.setRequestHandler(ListToolsRequestSchema, async () => { const tools = createUnifiedApiTools(); return { tools: tools, }; });
  • src/index.js:837-838 (registration)
    Dispatch/execution routing for 'api_call' in the CallToolRequestSchema handler switch statement.
    case "api_call": return await executeUnifiedApiCall(args);
  • Helper function to construct the complete request details (URL, headers, body) for the API call.
    function buildUnifiedApiRequest( method, path, pathParams = {}, queryParams = {}, headers = {}, body = null ) { const baseUrl = global.baseUrl; // 处理路径参数 let url = baseUrl + path; for (const [key, value] of Object.entries(pathParams)) { url = url.replace(`{${key}}`, encodeURIComponent(value)); } // 处理查询参数 const query = new URLSearchParams(); for (const [key, value] of Object.entries(queryParams)) { if (value !== undefined && value !== null) { query.append(key, value); } } if (query.toString()) { url += "?" + query.toString(); } // 处理请求头 const requestHeaders = { "User-Agent": config.http.userAgent, ...headers, }; // 处理请求体 let requestBody = null; if (body && (method === "POST" || method === "PUT" || method === "PATCH")) { requestBody = typeof body === "string" ? body : JSON.stringify(body); if (!requestHeaders["Content-Type"]) { requestHeaders["Content-Type"] = "application/json"; } } return { url, headers: requestHeaders, body: requestBody }; }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/zidong0822/swagger-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server