Skip to main content
Glama

call_endpoint

Execute API calls to the Swagger Petstore by specifying operation IDs and parameters, enabling interaction with endpoints discovered through list_endpoints.

Instructions

Call an endpoint in the Swagger Petstore - OpenAPI 3.0. Use list_endpoints first to discover available operationIds and their required parameters.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
operationIdYesThe operationId from list_endpoints, e.g. 'getPetById' or 'createUser'
parametersNoPath, query, and header parameters as key-value pairs
bodyNoRequest body for POST/PUT/PATCH requests (object or string)

Implementation Reference

  • The handler function for the `call_endpoint` tool. It validates the operationId, executes the request via `executeCall`, and formats the response.
    async ({ operationId, parameters, body }) => {
      const endpoint = findEndpoint(spec, operationId);
    
      if (!endpoint) {
        const available = getAllEndpoints(spec)
          .map((e) => e.operationId)
          .join(", ");
        return {
          content: [
            {
              type: "text" as const,
              text: `Unknown operationId: "${operationId}".\n\nAvailable operations: ${available}`,
            },
          ],
          isError: true,
        };
      }
    
      try {
        const result = await executeCall(spec, endpoint, parameters ?? {}, body);
        return {
          content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
        };
      } catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        return {
          content: [{ type: "text" as const, text: `Error calling ${operationId}: ${message}` }],
          isError: true,
        };
      }
    }
  • src/index.ts:65-113 (registration)
    Tool registration for `call_endpoint` including input schema validation using Zod.
    server.tool(
      "call_endpoint",
      `Call an endpoint in the ${apiTitle}. ` +
        "Use list_endpoints first to discover available operationIds and their required parameters.",
      {
        operationId: z
          .string()
          .describe("The operationId from list_endpoints, e.g. 'getPetById' or 'createUser'"),
        parameters: z
          .record(z.union([z.string(), z.number(), z.boolean()]))
          .optional()
          .describe("Path, query, and header parameters as key-value pairs"),
        body: z
          .unknown()
          .optional()
          .describe("Request body for POST/PUT/PATCH requests (object or string)"),
      },
      async ({ operationId, parameters, body }) => {
        const endpoint = findEndpoint(spec, operationId);
    
        if (!endpoint) {
          const available = getAllEndpoints(spec)
            .map((e) => e.operationId)
            .join(", ");
          return {
            content: [
              {
                type: "text" as const,
                text: `Unknown operationId: "${operationId}".\n\nAvailable operations: ${available}`,
              },
            ],
            isError: true,
          };
        }
    
        try {
          const result = await executeCall(spec, endpoint, parameters ?? {}, body);
          return {
            content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
          };
        } catch (err) {
          const message = err instanceof Error ? err.message : String(err);
          return {
            content: [{ type: "text" as const, text: `Error calling ${operationId}: ${message}` }],
            isError: true,
          };
        }
      }
    );
  • The actual logic that prepares and executes the HTTP request for the API endpoint.
    export async function executeCall(
      spec: OpenAPIV3.Document,
      endpoint: EndpointInfo,
      parameters: Record<string, string | number | boolean>,
      body: unknown
    ): Promise<ApiResponse> {
      const baseUrl = getBaseUrl(spec);
      let urlPath = endpoint.path;
      const queryParams: Record<string, string> = {};
      const headers: Record<string, string> = {
        Accept: "application/json",
        ...buildAuthHeaders(),
      };
    
      const params = (endpoint.operation.parameters ?? []) as OpenAPIV3.ParameterObject[];
    
      for (const param of params) {
        const value = parameters[param.name];
        if (value === undefined || value === null) {
          if (param.required) {
            throw new Error(`Missing required parameter: ${param.name} (${param.in})`);
          }
          continue;
        }
    
        const strValue = String(value);
    
        switch (param.in) {
          case "path":
            urlPath = urlPath.replace(`{${param.name}}`, encodeURIComponent(strValue));
            break;
          case "query":
            queryParams[param.name] = strValue;
            break;
          case "header":
            headers[param.name] = strValue;
            break;
          // cookie params are uncommon — skip for now
        }
      }
    
      let fullUrl = baseUrl + urlPath;
      if (Object.keys(queryParams).length > 0) {
        fullUrl += "?" + new URLSearchParams(queryParams).toString();
      }
    
      const fetchOptions: RequestInit = {
        method: endpoint.method.toUpperCase(),
        headers,
      };
    
      const methodHasBody = ["post", "put", "patch"].includes(endpoint.method.toLowerCase());
      if (methodHasBody && body !== undefined && body !== null) {
        if (typeof body === "string") {
          fetchOptions.body = body;
          headers["Content-Type"] = "text/plain";
        } else {
          fetchOptions.body = JSON.stringify(body);
          headers["Content-Type"] = "application/json";
        }
      }
    
      const response = await fetch(fullUrl, fetchOptions);
      const responseText = await response.text();
    
      let responseBody: unknown;
      const contentType = response.headers.get("content-type") ?? "";
      if (contentType.includes("application/json") || contentType.includes("+json")) {
        try {
          responseBody = JSON.parse(responseText);
        } catch {
          responseBody = responseText;
        }
      } else {
        responseBody = responseText;
      }
    
      const responseHeaders: Record<string, string> = {};
      response.headers.forEach((value, key) => {
        responseHeaders[key] = value;
      });
    
      return {
        status: response.status,
        statusText: response.statusText,
        headers: responseHeaders,
        body: responseBody,
      };
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. While it mentions the need to use 'list_endpoints' first for discovery, it doesn't describe what happens when the tool is invoked (e.g., HTTP method implications, error handling, authentication requirements, rate limits, or what the response looks like). For a tool that makes API calls, this leaves significant behavioral gaps.

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

Conciseness5/5

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

The description is perfectly concise - two sentences that each earn their place. The first sentence establishes the core purpose, and the second provides essential usage guidance. There's zero waste or redundancy.

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?

For a tool that makes API calls with 3 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain what the tool returns, how errors are handled, authentication requirements, or the implications of different HTTP methods. The usage guidance is helpful but doesn't compensate for the missing behavioral context needed for effective tool invocation.

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%, so the schema already documents all three parameters thoroughly. The description adds minimal value beyond what the schema provides - it mentions 'operationId' and 'parameters' in the context of discovery but doesn't provide additional semantic context about how these parameters interact or when to use 'body' versus 'parameters'. Baseline 3 is appropriate when the schema does the heavy lifting.

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

Purpose4/5

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

The description clearly states the action ('Call an endpoint') and the target resource ('in the Swagger Petstore - OpenAPI 3.0'), providing a specific verb+resource combination. However, it doesn't explicitly distinguish this tool from its sibling 'list_endpoints' beyond mentioning it should be used first for discovery, which is more of a usage guideline than a purpose distinction.

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

Usage Guidelines5/5

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

The description explicitly states when to use this tool ('Use list_endpoints first to discover available operationIds and their required parameters'), providing clear guidance on prerequisites and the relationship with the sibling tool. This tells the agent exactly how to approach using this tool effectively.

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/saurav61091/mcp-openapi'

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