Razorpay Model Context Protocol (MCP) Server

repository·main·Indexed 42 days ago

https://github.com/razorpay/razorpay-mcp-server

An official Model Context Protocol implementation that enables AI agents and tools to interact with the Razorpay payment ecosystem. It provides a standardized set of tools for managing payments, orders, refunds, and payment links, allowing AI models to automate payment workflows and build agentic applications via the Razorpay API.

Tokens
9.3K
Snippets
26
Records
34
Agent score
52%

What's inside Razorpay MCP Server

  1. Overview of Razorpay MCP Server

    main

    The Razorpay MCP Server is an implementation of the Model Context Protocol (MCP) that provides a bridge between AI tools (like LLMs and AI agents) and the Razorpay API ecosystem. It allows developers to build agentic applications and automate payment workflows by exposing Razorpay's payment processing capabilities as tools that an AI can call.

    Key Capabilities:

    • Workflow Automation: Automate routine payment management tasks.
    • Agentic Applications: Build AI-powered tools that can interact directly with payments, orders, refunds, and settlements.
  2. Tool implementation structure and naming conventions

    main

    New tools should be defined using the mcpgo.Tool interface. Each tool consists of a parameter definition list and a handler function that processes the request.

    Naming Conventions:

    • Fetch methods: fetch_resource
    • Create methods: create_resource
    • FetchAll methods: fetch_all_resources
    // ToolName returns a tool that [description of what it does]
    func ToolName(
        log *slog.Logger,
        client *rzpsdk.Client,
    ) mcpgo.Tool {
        parameters := []mcpgo.ToolParameter{
            // Parameters defined here
        }
    
        handler := func(
            ctx context.Context,
            r mcpgo.CallToolRequest,
        ) (*mcpgo.ToolResult, error) {
            // Parameter validation
            // API call
            // Response handling
            return mcpgo.NewToolResultJSON(response)
        }
    
        return mcpgo.NewTool(
            "tool_name",
            "A description of the tool. NOTE: Add any exceptions/rules if relevant for the LLMs.",
            parameters,
            handler,
        )
    }
  3. How mcpgo abstracts the MCP SDK

    main

    The mcpgo package acts as an abstraction layer over the github.com/mark3labs/mcp-go library. It is designed to:

    1. Isolate Dependencies: All imports of mark3labs/mcp-go are confined to the mcpgo package.
    2. Enable Future Compatibility: The package provides clean interfaces (Server, Tool, TransportServer) so that the underlying implementation can be swapped for an official MCP SDK without changing the application logic.
    3. Simplify the API: It exposes only the necessary functionality required by the application through a focused API.
    4. Standardize Error Handling: It implements robust error handling patterns instead of relying on panics.
  4. Validate parameters using the fluent validator pattern

    main

    Inside the tool handler, use NewValidator and method chaining to validate parameters and populate a payload map for the API call. This pattern allows you to collect multiple validation errors before proceeding.

    Workflow:

    1. Create a payload map: payload := make(map[string]interface{}).
    2. Chain validation methods (e.g., ValidateAndAddRequiredString).
    3. Check for errors using validator.HandleErrorsIfAny().
    4. If no errors, use the payload map for the SDK call.
    // Create a new validator
    v := NewValidator(&r)
    
    // Create a map for API request parameters
    payload := make(map[string]interface{})
    
    // Validate and add parameters to the payload with method chaining
    v.ValidateAndAddRequiredString(payload, "id").
      ValidateAndAddOptionalString(payload, "description").
      ValidateAndAddRequiredInt(payload, "amount").
      ValidateAndAddOptionalInt(payload, "limit")
    
    // Check for validation errors
    if result, err := validator.HandleErrorsIfAny(); result != nil {
    	return result, err
    }
    
    // Proceed with API call using validated parameters in payload
  5. Register tools in toolsets

    main

    Tools are organized into toolsets by resource type. Each toolset distinguishes between read-only tools (AddReadTools) and write tools (AddWriteTools). This allows the server to respect read-only modes.

    To register a tool, add it to the appropriate method in NewToolSets within pkg/razorpay/tools.go.

    // NewToolSets creates and configures all available toolsets
    func NewToolSets(
        log *slog.Logger,
        client *rzpsdk.Client,
        enabledToolsets []string,
        readOnly bool,
    ) (*toolsets.ToolsetGroup, error) {
        toolsetGroup := toolsets.NewToolsetGroup(readOnly)
    
        payments := toolsets.NewToolset("payments", "Razorpay Payments related tools").
            AddReadTools(
                FetchPayment(log, client),
            ).
            AddWriteTools(
                // Add write tools here
            )
    
        // ... other toolsets ...
    
        toolsetGroup.AddToolset(payments)
        // ... add other toolsets ...
    
        return toolsetGroup, nil
    }
  6. Create an MCP server with mcpgo

    main

    To create an MCP server, use mcpgo.NewServer with a name, version, and optional configuration options like mcpgo.WithLogging() and mcpgo.WithToolCapabilities(true). Once the server is configured, you can add tools using server.AddTools(tool) and start the server using a transport implementation like mcpgo.NewStdioServer(server). For a stdio server, call stdioServer.Listen(ctx, os.Stdin, os.Stdout).

    // Create a server
    server := mcpgo.NewServer(
        "my-server",
        "1.0.0",
        mcpgo.WithLogging(),
        mcpgo.WithToolCapabilities(true),
    )
    
    // ... define and add tools ...
    
    // Create and run a stdio server
    stdioServer, err := mcpgo.NewStdioServer(server)
    if err != nil {
        log.Fatalf("Failed to create stdio server: %v", err)
    }
    err = stdioServer.Listen(context.Background(), os.Stdin, os.Stdout)
    if err != nil {
        log.Fatalf("Server error: %v", err)
    }
  7. How to create new Razorpay API tools

    main

    To add a new Razorpay API tool to the MCP server, follow these steps:

    1. Consult API Docs: Find the endpoint at https://razorpay.com/docs/api/.
    2. Identify SDK Method: Find the equivalent function in the razorpay go sdk.
    3. Implement Tool Function: Create a new tool function in the appropriate resource file within pkg/razorpay. Implement parameter validation and call the SDK.
    4. Register Tool: Add the tool to the appropriate toolset in server.go (specifically within the NewToolSets function).
    5. Update Documentation: Add the new tool to the "Available Tools" section in the main README.md.
    /* 
    1. Locate API docs
    2. Identify SDK call
    3. Create tool function
    4. Register in server.go
    5. Update README.md
    */
  8. Build Local MCP Server from Source

    main

    To build the Razorpay MCP server binary directly from the Go source code:

    1. Clone the repository:
      git clone https://github.com/razorpay/razorpay-mcp-server.git
      cd razorpay-mcp-server
    2. Build the binary:
      go build -o razorpay-mcp-server ./cmd/razorpay-mcp-server

    Once built, you can use the binary path in your MCP client configuration (e.g., VS Code) using the stdio transport.

    git clone https://github.com/razorpay/razorpay-mcp-server.git
    cd razorpay-mcp-server
    go build -o razorpay-mcp-server ./cmd/razorpay-mcp-server
  9. Deploy Local MCP Server using Docker (Claude Desktop)

    main

    If you prefer to run the server locally using Docker, add this to your claude_desktop_config.json. This uses the official razorpay/mcp image and requires your API credentials as environment variables.

    {
        "mcpServers": {
            "razorpay-mcp-server": {
                "command": "docker",
                "args": [
                    "run",
                    "--rm",
                    "-i",
                    "-e",
                    "RAZORPAY_KEY_ID",
                    "-e",
                    "RAZORPAY_KEY_SECRET",
                    "razorpay/mcp"
                ],
                "env": {
                    "RAZORPAY_KEY_ID": "your_razorpay_key_id",
                    "RAZORPAY_KEY_SECRET": "your_razorpay_key_secret"
                }
            }
        }
    }
  10. Configure Remote MCP Server in Claude Desktop

    main

    Add this configuration to your claude_desktop_config.json to use the hosted Remote MCP Server. You must replace <Merchant Token> with the Base64-encoded token generated from your API Key and Secret.

    {
      "mcpServers": {
        "rzp-mcp-server": {
          "command": "npx",
          "args": [
            "mcp-remote",
            "https://mcp.razorpay.com/mcp",
            "--header",
            "Authorization: Basic <Merchant Token>"
          ]
        }
      }
    }
  11. Configure Remote MCP Server in VS Code

    main

    Add the following to your VS Code settings (JSON) to use the Remote MCP Server. This configuration uses a promptString input to securely ask for your Merchant Token when the server starts.

    {
      "mcp": {
        "inputs": [
          {
            "type": "promptString",
            "id": "merchant_token",
            "description": "Razorpay Merchant Token",
            "password": true
          }
        ],
        "servers": {
          "razorpay-remote": {
            "command": "npx",
            "args": [
              "mcp-remote",
              "https://mcp.razorpay.com/mcp",
              "--header",
              "Authorization: Basic ${input:merchant_token}"
            ]
          }
        }
      }
    }