UNPKG

@mastercard/developers-agent-toolkit

Version:

Agent Toolkit for Mastercard Developers Platform

502 lines (478 loc) 16.9 kB
// src/modelcontextprotocol/index.ts import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; // src/shared/tools/documentation/getDocumentation.ts import { z as z2 } from "zod"; // src/shared/api/index.ts import { z } from "zod"; import fetch from "node-fetch"; var PathSchema = z.string().min(1, "Path must be a non-empty string").startsWith("/", "Path must start with /"); var MastercardAPIClient = class { baseUrl = new URL("https://developer.mastercard.com/"); /** * Makes HTTP request to the specified endpoint */ async request(endpoint, params) { const url = new URL(endpoint, this.baseUrl); if (url.hostname !== this.baseUrl.hostname) { throw new Error("Invalid endpoint: URL hostname mismatch"); } if (params) { const searchParams = new URLSearchParams(params); url.search = searchParams.toString(); } const response = await fetch(url, { method: "GET", headers: { "User-Agent": "mastercard-developers-mcp" } }); if (!response.ok) { throw new Error( `Request failed with status ${response.status} - ${url.toString()}` ); } return response.text(); } /** * Retrieve a list of all available Mastercard services */ async listServices() { return this.request("/llms.txt", { absolute_urls: "false" }); } /** * Get documentation overview for a specific service */ async getDocumentation(serviceId) { return this.request(`/${serviceId}/documentation/llms.txt`, { absolute_urls: "false" }); } /** * Get content for a specific documentation section */ async getDocumentationSection(serviceId, sectionId) { return this.request(`/${serviceId}/documentation/llms-full.txt`, { absolute_urls: "false", section_id: sectionId }); } /** * Get a specific documentation page */ async getDocumentationPage(pagePath) { const validatedPath = PathSchema.parse(pagePath); return this.request(validatedPath); } /** * Get API operations for a specific API specification */ async getApiOperations(apiSpecificationPath) { const validatedPath = PathSchema.parse(apiSpecificationPath); return this.request(validatedPath, { summary: "true" }); } /** * Get detailed information for a specific API operation */ async getApiOperationDetails(apiSpecificationPath, method, path) { const validatedApiPath = PathSchema.parse(apiSpecificationPath); return this.request(validatedApiPath, { method, path }); } }; var api = new MastercardAPIClient(); var api_default = api; // src/shared/tools/documentation/getDocumentation.ts var getDescription = (context) => { const baseDescription = `Provides an overview of all available documentation for a specific Mastercard service including section titles, descriptions, and navigation links.`; if (context.serviceId) { return `${baseDescription} Uses the configured service: ${context.serviceId}`; } return `${baseDescription} It takes one argument: - serviceId (str): The unique identifier of the Mastercard service (e.g., 'send', 'loyalty', 'locations')`; }; var getParameters = (context) => { if (context.serviceId) { return z2.object({}); } return z2.object({ serviceId: z2.string().min(1).describe( "The unique identifier of the Mastercard service (e.g., 'send', 'loyalty', 'locations')" ) }); }; var execute = async (context, params) => { const serviceId = context.serviceId || params.serviceId; return await api_default.getDocumentation(serviceId); }; var getDocumentation = (context) => ({ method: "get-documentation", name: "Get Documentation", description: getDescription(context), parameters: getParameters(context), execute: (params) => execute(context, params) }); // src/shared/tools/documentation/getDocumentationSection.ts import { z as z3 } from "zod"; var getDescription2 = (context) => { const baseDescription = ` Retrieves the complete content for a specific documentation section. IMPORTANT: A section is not a single page, but rather a collection of pages that are grouped together. `; if (context.serviceId) { return `${baseDescription} Uses the configured service: ${context.serviceId} It takes one argument: - sectionId (str): The specific section identifier within the service documentation (e.g., 'getting-started', 'api-reference')`; } return `${baseDescription} It takes two arguments: - serviceId (str): The unique identifier of the Mastercard service (e.g., 'send', 'loyalty', 'locations') - sectionId (str): The specific section identifier within the service documentation (e.g., 'getting-started', 'api-reference') `; }; var getParameters2 = (context) => { const baseParams = { sectionId: z3.string().min(1).describe( "The specific section identifier within the service documentation (e.g., 'getting-started', 'api-reference')" ) }; if (context.serviceId) { return z3.object(baseParams); } return z3.object({ serviceId: z3.string().min(1).describe( "The unique identifier of the Mastercard service (e.g., 'send', 'loyalty', 'locations')" ), ...baseParams }); }; var execute2 = async (context, params) => { const serviceId = context.serviceId || params.serviceId; return await api_default.getDocumentationSection(serviceId, params.sectionId); }; var getDocumentationSection = (context) => ({ method: "get-documentation-section-content", name: "Get Documentation Section Content", description: getDescription2(context), parameters: getParameters2(context), execute: (params) => execute2(context, params) }); // src/shared/tools/documentation/getDocumentationPage.ts import { z as z4 } from "zod"; var getDescription3 = (_context) => { return `Retrieves the complete content of a specific documentation page. Takes one argument: - pagePath (str): The full path to the documentation page (e.g., '/send/documentation/use-cases/index.md')`; }; var getParameters3 = (_context) => { return z4.object({ pagePath: z4.string().min(1).describe( "The full path to the documentation page (e.g., '/send/documentation/use-cases/index.md')" ) }); }; var execute3 = async (_context, params) => { return await api_default.getDocumentationPage(params.pagePath); }; var getDocumentationPage = (context) => ({ method: "get-documentation-page", name: "Get Documentation Page", description: getDescription3(context), parameters: getParameters3(context), execute: (params) => execute3(context, params) }); // src/shared/tools/documentation/getOAuth10aGuide.ts import { z as z5 } from "zod"; var getDescription4 = (_context) => { return `Retrieves the comprehensive OAuth 1.0a integration guide including step-by-step instructions, code examples, and best practices for Mastercard APIs.`; }; var getParameters4 = (_context) => { return z5.object({}); }; var execute4 = async (_context, _params) => { return await api_default.getDocumentationPage( "/platform/documentation/authentication/using-oauth-1a-to-access-mastercard-apis/index.md" ); }; var getOAuth10aGuide = (context) => ({ method: "get-oauth10a-integration-guide", name: "Get OAuth 1.0a Integration Guide", description: getDescription4(context), parameters: getParameters4(context), execute: (params) => execute4(context, params) }); // src/shared/tools/documentation/getOpenBankingGuide.ts import { z as z6 } from "zod"; var getDescription5 = (_context) => { return `Retrieves the comprehensive Open Banking integration guide including setup instructions, API usage examples, and implementation best practices.`; }; var getParameters5 = (_context) => { return z6.object({}); }; var execute5 = async (_context, _params) => { return await api_default.getDocumentationPage( "/open-banking-us/documentation/quick-start-guide/index.md" ); }; var getOpenBankingGuide = (context) => ({ method: "get-openbanking-integration-guide", name: "Get Open Banking Integration Guide", description: getDescription5(context), parameters: getParameters5(context), execute: (params) => execute5(context, params) }); // src/shared/tools/services/getServicesList.ts import { z as z7 } from "zod"; var getDescription6 = (_context) => { return `Lists all available Mastercard Developers Products and Services with their basic information including title, description, and service id. IMPORTANT: The response contains both 'Products' (business offerings) and 'Services' (technical APIs with serviceIds). Use "serviceId" for each service for any tools that require serviceId as the parameter. `; }; var getParameters6 = (_context) => { return z7.object({}); }; var execute6 = async (_context, _params) => { return await api_default.listServices(); }; var getServicesList = (context) => ({ method: "get-services-list", name: "Get Services List", description: getDescription6(context), parameters: getParameters6(context), execute: (params) => execute6(context, params) }); // src/shared/tools/operations/getApiOperationList.ts import { z as z8 } from "zod"; var getDescription7 = (context) => { const baseDescription = `Provides a summary of all API operations for a specific Mastercard API specification including HTTP methods, request paths, titles, and descriptions.`; if (context.apiSpecificationPath) { return `${baseDescription} Uses the configured API specification: ${context.apiSpecificationPath}`; } return `${baseDescription} It takes one argument: - apiSpecificationPath (str): The path to the API specification file e.g., '/open-banking-us/swagger/openbanking-us.yaml')`; }; var getParameters7 = (context) => { if (context.apiSpecificationPath) { return z8.object({}); } return z8.object({ apiSpecificationPath: z8.string().describe( "The path to the API specification file (e.g., /open-banking-us/swagger/openbanking-us.yaml)" ) }); }; var execute7 = async (context, params) => { if (context.apiSpecificationPath) { return await api_default.getApiOperations(context.apiSpecificationPath); } else { return await api_default.getApiOperations(params.apiSpecificationPath); } }; var getApiOperationList = (context) => ({ method: "get-api-operation-list", name: "Get API Operation List", description: getDescription7(context), parameters: getParameters7(context), execute: (params) => execute7(context, params) }); // src/shared/tools/operations/getApiOperationDetails.ts import { z as z9 } from "zod"; var getDescription8 = (context) => { const baseDescription = `Provides detailed information about a specific API operation including parameter definitions, request and response schemas, and technical specifications for successful API calls.`; if (context.apiSpecificationPath) { return `${baseDescription} Uses the configured API specification: ${context.apiSpecificationPath} It takes two arguments: - method (str): The HTTP method of the operation (e.g., GET, POST, PUT, DELETE) - path (str): The API endpoint path from the specification (e.g., /payments, /accounts/{id})`; } return `${baseDescription} It takes three arguments: - apiSpecificationPath (str): The path to the API specification file (e.g. The path would be /open-banking-us/swagger/openbanking-us.yaml for https://static.developer.mastercard.com/content/open-banking-us/swagger/openbanking-us.yaml, https://developer.mastercard.com/open-banking-us/swagger/openbanking-us.yaml, or /open-banking-us/swagger/openbanking-us.yaml) - method (str): The HTTP method of the operation (e.g., GET, POST, PUT, DELETE) - path (str): The API endpoint path from the specification (e.g., /payments, /accounts/{id})`; }; var getParameters8 = (context) => { const baseParams = { method: z9.string().describe( "The HTTP method of the operation (e.g., GET, POST, PUT, DELETE)" ), path: z9.string().describe( "The API endpoint path from the specification (e.g., /payments, /accounts/{id})" ) }; if (context.apiSpecificationPath) { return z9.object(baseParams); } return z9.object({ apiSpecificationPath: z9.string().describe( "The path to the API specification (e.g., /open-banking-us/swagger/openbanking-us.yaml)" ), ...baseParams }); }; var execute8 = async (context, params) => { if (context.apiSpecificationPath) { return await api_default.getApiOperationDetails( context.apiSpecificationPath, params.method, params.path ); } else { return await api_default.getApiOperationDetails( params.apiSpecificationPath, params.method, params.path ); } }; var getApiOperationDetails = (context) => ({ method: "get-api-operation-details", name: "Get API Operation Details", description: getDescription8(context), parameters: getParameters8(context), execute: (params) => execute8(context, params) }); // src/shared/tools/index.ts var tools = (context) => [ // Services getServicesList(context), // Documentation getDocumentation(context), getDocumentationSection(context), getDocumentationPage(context), getOAuth10aGuide(context), getOpenBankingGuide(context), // API Operations getApiOperationList(context), getApiOperationDetails(context) ]; // package.json var version = "0.1.1"; // src/modelcontextprotocol/index.ts var MastercardDevelopersAgentToolkit = class extends McpServer { constructor(config = {}) { super({ name: "mastercard-developers-mcp", version, capabilities: { tools: {} } }); this.registerAllTools(config); } registerAllTools(config) { const context = buildContext(config); const availableTools = tools(context); const enabledTools = availableTools.filter((tool) => { if (context.serviceId && tool.method === "get-services-list") { return false; } return true; }); enabledTools.forEach((tool) => { this.tool( tool.method, tool.description, tool.parameters.shape, async (params) => { try { const result = await tool.execute(params); return { content: [{ type: "text", text: result }] }; } catch (error) { const message = error instanceof Error ? error.message : String(error); return { content: [ { type: "text", text: message, isError: true } ] }; } } ); }); } }; function buildContext(config) { const context = {}; if (config.service != null) { const serviceId = parseServiceIdFromUrl(config.service); if (serviceId == null) { throw new Error( "Invalid service URL provided. It should be in the format: https://developer.mastercard.com/<service-id>/documentation/**" ); } context.serviceId = serviceId; } else if (config.apiSpecification != null) { const parsed = parseAPISpecificationPathAndServiceId( config.apiSpecification ); if (parsed?.serviceId == null || parsed?.apiSpecificationPath == null) { throw new Error( "Invalid API specification path provided. It should be in the format: https://static.developer.mastercard.com/content/<service-id>/swagger/<nested-file-path>.yaml" ); } context.serviceId = parsed.serviceId; context.apiSpecificationPath = parsed.apiSpecificationPath; } return context; } function validateServiceId(serviceId) { return /^[a-z]+(?:-[a-z0-9]+)*$/i.test(serviceId); } function parseServiceIdFromUrl(input) { try { const url = new URL(input); if (url.hostname !== "developer.mastercard.com") { return null; } const pathParts = url.pathname.split("/").filter((part) => part.length > 0); if (pathParts.length >= 2 && pathParts[1] === "documentation") { const serviceId = pathParts[0]; if (serviceId && validateServiceId(serviceId)) { return serviceId.toLowerCase(); } } return null; } catch { return null; } } function parseAPISpecificationPathAndServiceId(input) { try { const url = new URL(input); if (url.hostname !== "static.developer.mastercard.com") { return null; } const pathParts = url.pathname.split("/").filter((part) => part.length > 0); if (pathParts.length >= 4 && pathParts[0] === "content" && pathParts[2] === "swagger") { const serviceId = pathParts[1]; const file = pathParts.slice(3).join("/"); if (serviceId && file && validateServiceId(serviceId) && file.endsWith(".yaml")) { return { serviceId: serviceId.toLowerCase(), apiSpecificationPath: `/${serviceId.toLowerCase()}/swagger/${file}` }; } } return null; } catch { return null; } } export { MastercardDevelopersAgentToolkit, buildContext }; //# sourceMappingURL=index.mjs.map