Skip to main content
Glama
zidong0822
by zidong0822

api_call

Execute API calls by specifying HTTP methods, paths, parameters, and headers to interact with REST APIs defined in Swagger specifications.

Instructions

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

Input Schema

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

Implementation Reference

  • The primary handler function for the 'api_call' tool. It destructures the input arguments, builds the request using buildUnifiedApiRequest, performs an HTTP fetch request with timeout and retry logic, handles JSON/text responses, and returns the response details.
    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}`
      );
    }
  • The schema definition for the 'api_call' tool, including name, description, and detailed inputSchema specifying properties for HTTP method, path, pathParams, queryParams, headers, body, with required fields.
    {
      name: "api_call",
      description: `调用${swaggerDoc.info.title} API的通用工具。支持所有HTTP方法和路径。`,
      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:832-852 (registration)
    The MCP CallTool request handler registration. It uses a switch statement on the tool name to dispatch 'api_call' calls to the executeUnifiedApiCall handler function.
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const { name, arguments: args } = request.params;
    
      try {
        switch (name) {
          case "api_call":
            return await executeUnifiedApiCall(args);
          case "api_list_endpoints":
            return await listEndpoints(args);
          case "api_get_endpoint_info":
            return await getEndpointDetails(args);
          default:
            throw new McpError(ErrorCode.InvalidRequest, `未知工具: ${name}`);
        }
      } catch (error) {
        if (error instanceof McpError) {
          throw error;
        }
        throw new McpError(ErrorCode.InternalError, error.message);
      }
    });
  • src/index.js:824-829 (registration)
    The MCP ListTools request handler registration, which dynamically generates and returns the list of available tools, including 'api_call', by calling createUnifiedApiTools().
    server.setRequestHandler(ListToolsRequestSchema, async () => {
      const tools = createUnifiedApiTools();
      return {
        tools: tools,
      };
    });
  • Helper function used by the api_call handler to construct the complete request object (URL with path/query params, headers, body) from the input arguments.
    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 };
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool supports all HTTP methods and paths, implying it can perform various operations (e.g., GET, POST, DELETE), but does not disclose critical behavioral traits such as authentication requirements, rate limits, error handling, or whether it's safe or destructive. For a general-purpose API tool with no annotations, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise with two sentences that directly state the tool's general function and capabilities. It is front-loaded and wastes no words, though it could be slightly more informative without losing efficiency. The structure is clear but minimal, earning a high score for brevity and directness.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (6 parameters, no output schema, no annotations), the description is incomplete. It lacks details on behavioral aspects like authentication, error handling, or response formats, which are crucial for a general API tool. Without annotations or output schema, the description should provide more context to guide the agent effectively, but it falls short, leaving significant gaps in understanding.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, with detailed descriptions for all parameters in the input schema (e.g., 'HTTP方法' for method, 'API路径' for path). The description adds no additional meaning beyond the schema, as it only mentions supporting all HTTP methods and paths without explaining parameter interactions or usage. With high schema coverage, the baseline score of 3 is appropriate, as the schema adequately documents parameters.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states the tool '调用示例API API的通用工具' (calls example API general tool) and '支持所有HTTP方法和路径' (supports all HTTP methods and paths), which provides a vague purpose. It mentions the general function but lacks specificity about what resources it operates on or how it differs from siblings like 'api_get_endpoint_info' and 'api_list_endpoints'. The description is not tautological but remains broad without clear differentiation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It does not mention any context, prerequisites, or exclusions, such as when to choose this over sibling tools like 'api_get_endpoint_info' for endpoint details or 'api_list_endpoints' for listing. Without explicit or implied usage instructions, the agent lacks direction on appropriate tool selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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