Skip to main content
Glama
martin-1103
by martin-1103

create_endpoint

Create new API endpoints by defining HTTP methods, URLs, headers, and documentation to organize and manage your API catalog within designated folders.

Instructions

Create a new endpoint in a folder

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
nameYesEndpoint name (required)
methodYesHTTP method (required)
urlYesEndpoint URL (required)
folder_idYesFolder ID to create endpoint in (required)
descriptionNoEndpoint description (optional)
headersNoRequest headers as key-value pairs
bodyNoRequest body (JSON string)
purposeNoBusiness purpose - what this endpoint does (optional)
request_paramsNoParameter documentation: {param_name: "description"}
response_schemaNoResponse field documentation: {field_name: "description"}
header_docsNoHeader documentation: {header_name: "description"}

Implementation Reference

  • Main handler function that executes the create_endpoint tool: extracts args, validates data (with folder suggestions), formats request, makes POST API call to backend, handles timeouts/errors with user-friendly messages, returns formatted response.
    export async function handleCreateEndpoint(args: Record<string, any>): Promise<McpToolResponse> {
      try {
        const { configManager, backendClient } = await getEndpointDependencies();
    
        const name = args.name as string;
        const method = args.method as HttpMethod;
        const url = args.url as string;
        const folderId = args.folder_id as string;
        const description = args.description as string | undefined;
        const purpose = args.purpose as string | undefined;
        const headers = args.headers as Record<string, string> | undefined;
        const body = args.body as string | undefined;
        const requestParams = args.request_params as Record<string, string> | undefined;
        const responseSchema = args.response_schema as Record<string, string> | undefined;
        const headerDocs = args.header_docs as Record<string, string> | undefined;
    
        // Validate input
        const validationErrors = validateEndpointData({ name, method, url, folder_id: folderId });
        if (validationErrors.length > 0) {
          // Check if folder_id is the only error and provide helpful suggestions
          if (validationErrors.length === 1 && validationErrors[0] === 'Folder ID is required') {
            const foldersMessage = await getFolderSuggestions(configManager, backendClient);
            throw new Error(`Folder ID is required\n\n${foldersMessage}`);
          }
          throw new Error(validationErrors.join('\n'));
        }
    
        // Create endpoint
        const apiEndpoints = getApiEndpoints();
        const endpoint = apiEndpoints.getEndpoint('endpointCreate', { id: folderId });
    
        const requestBody = JSON.stringify({
          name: name.trim(),
          method,
          url: url.trim(),
          description: description?.trim() || null,
          purpose: purpose?.trim() || null,
          headers: formatHeaders(headers || {}),
          body: formatBody(body) || null,
          request_params: requestParams || null,
          response_schema: responseSchema || null,
          header_docs: headerDocs || null
        });
    
        console.error(`[EndpointTools] Creating endpoint at: ${endpoint}`);
        console.error(`[EndpointTools] Folder ID: ${folderId}`);
        console.error(`[EndpointTools] Base URL: ${backendClient.getBaseUrl()}`);
        console.error(`[EndpointTools] Token: ${backendClient.getToken().substring(0, 20)}...`);
        console.error(`[EndpointTools] Request Body: ${requestBody}`);
    
        // Create AbortController for timeout
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 second timeout
    
        let apiResponse;
        try {
          const result = await fetch(`${backendClient.getBaseUrl()}${endpoint}`, {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${backendClient.getToken()}`,
              'Content-Type': 'application/json'
            },
            body: requestBody,
            signal: controller.signal
          });
    
          clearTimeout(timeoutId);
    
          if (!result.ok) {
            throw new Error(`HTTP ${result.status}: ${result.statusText}`);
          }
    
          const data = await result.json() as EndpointCreateResponse;
    
          apiResponse = {
            success: data.success,
            data: data.data,
            message: data.message,
            status: result.status
          };
        } catch (networkError) {
          clearTimeout(timeoutId);
          throw networkError;
        }
    
        if (!apiResponse.success) {
          let errorMessage = `Failed to create endpoint: ${apiResponse.message || 'Unknown error'}`;
    
          // Provide helpful error messages for common scenarios
          if (apiResponse.status === 404) {
            errorMessage = `Folder with ID '${folderId}' not found. Cannot create endpoint.\n\n`;
            errorMessage += `Please check:\n`;
            errorMessage += `• Folder ID '${folderId}' is correct\n`;
            errorMessage += `• You have access to this folder\n`;
            errorMessage += `• Folder exists in the project\n\n`;
            errorMessage += `Use get_folders to see available folders, or create a new folder first.`;
          } else if (apiResponse.status === 403) {
            errorMessage = `Access denied. You don't have permission to create endpoints in this folder.\n\n`;
            errorMessage += `Please check:\n`;
            errorMessage += `• You are a member of the project\n`;
            errorMessage += `• Your account has write permissions for this folder`;
          } else if (apiResponse.status === 400) {
            errorMessage = `Invalid endpoint data. Please check:\n`;
            errorMessage += `• Endpoint name is not empty\n`;
            errorMessage += `• URL is valid and properly formatted\n`;
            errorMessage += `• HTTP method is valid (GET, POST, PUT, DELETE, PATCH)\n`;
            errorMessage += `• Headers are valid JSON if provided`;
          }
    
          throw new Error(errorMessage);
        }
    
        if (apiResponse.success && apiResponse.data) {
          const createText = formatEndpointCreateText(apiResponse.data);
    
          return {
            content: [
              {
                type: 'text',
                text: createText
              }
            ]
          };
        } else {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Failed to create endpoint: ${apiResponse.message || 'Unknown error'}`
              }
            ],
            isError: true
          };
        }
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `❌ Endpoint creation error: ${error instanceof Error ? error.message : 'Unknown error'}`
            }
          ],
          isError: true
        };
      }
    }
  • Defines the tool schema: name 'create_endpoint', description, and detailed inputSchema with required/optional properties for endpoint creation.
    // Tool: create_endpoint
    export const createEndpointTool: McpTool = {
      name: 'create_endpoint',
      description: 'Create a new endpoint in a folder',
      inputSchema: {
        type: 'object',
        properties: {
          name: {
            type: 'string',
            description: 'Endpoint name (required)'
          },
          method: {
            type: 'string',
            description: 'HTTP method (required)',
            enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']
          },
          url: {
            type: 'string',
            description: 'Endpoint URL (required)'
          },
          folder_id: {
            type: 'string',
            description: 'Folder ID to create endpoint in (required)'
          },
          description: {
            type: 'string',
            description: 'Endpoint description (optional)'
          },
          headers: {
            type: 'object',
            description: 'Request headers as key-value pairs',
            additionalProperties: {
              type: 'string',
              description: 'Header value'
            }
          },
          body: {
            type: 'string',
            description: 'Request body (JSON string)'
          },
          purpose: {
            type: 'string',
            description: 'Business purpose - what this endpoint does (optional)'
          },
          request_params: {
            type: 'object',
            description: 'Parameter documentation: {param_name: "description"}',
            additionalProperties: {
              type: 'string',
              description: 'Parameter description'
            }
          },
          response_schema: {
            type: 'object',
            description: 'Response field documentation: {field_name: "description"}',
            additionalProperties: {
              type: 'string',
              description: 'Response field description'
            }
          },
          header_docs: {
            type: 'object',
            description: 'Header documentation: {header_name: "description"}',
            additionalProperties: {
              type: 'string',
              description: 'Header description'
            }
          }
        },
        required: ['name', 'method', 'url', 'folder_id']
      }
    };
  • Registers 'create_endpoint' by mapping createEndpointTool.name to handleCreateEndpoint in the handlers object.
    export function createEndpointToolHandlers(): Record<string, EndpointToolHandler> {
      return {
        [listEndpointsTool.name]: handleListEndpoints,
        [getEndpointDetailsTool.name]: handleGetEndpointDetails,
        [createEndpointTool.name]: handleCreateEndpoint,
        [updateEndpointTool.name]: handleUpdateEndpoint,
        [deleteEndpointTool.name]: handleDeleteEndpoint
      };
    }
  • Top-level registration that includes endpoint handlers (including create_endpoint) in the complete tool handlers map.
    export function createAllToolHandlers(): Record<string, (args: any) => Promise<McpToolResponse>> {
      return {
        ...createCoreToolHandlers(),
        ...createAuthToolHandlers(),
        ...createEnvironmentToolHandlers(),
        ...createFolderToolHandlers(),
        ...createEndpointToolHandlers(),
        ...createTestingToolHandlers(),
        ...createFlowToolHandlers()
      };
    }

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/martin-1103/mcp2'

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