Skip to main content
Glama
cURL MCP Server
by sixees

cURL MCP Server

A security-hardened MCP server that gives LLMs the ability to make HTTP requests via cURL. Use it as a standalone server, extend it programmatically, or define APIs declaratively with YAML.

Key features:

  • Security-first — SSRF protection, DNS rebinding prevention, rate limiting, input validation

  • Extensible — McpCurlServer class with hooks, custom tools, and configuration

  • YAML-driven — Define API endpoints declaratively and generate MCP tools automatically

  • Two tools — curl_execute for HTTP requests, jq_query for querying saved JSON files

Quick Start: MCP Server

Claude Code

claude mcp add curl -- npx -y github:sixees/mcp-curl

Or add to .mcp.json:

{
  "mcpServers": {
    "curl": {
      "command": "npx",
      "args": [
        "-y",
        "github:sixees/mcp-curl"
      ]
    }
  }
}

Claude Desktop

Add to your config file:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

  • Windows: %APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "curl": {
      "command": "npx",
      "args": [
        "-y",
        "github:sixees/mcp-curl"
      ]
    }
  }
}

Related MCP server: curl-mcp

Quick Start: Standalone

# Stdio transport (default)
npx -y github:sixees/mcp-curl

# HTTP transport
TRANSPORT=http PORT=3000 npx -y github:sixees/mcp-curl

# HTTP with authentication
TRANSPORT=http PORT=3000 MCP_AUTH_TOKEN=your-secret npx -y github:sixees/mcp-curl

Or clone and build locally:

git clone https://github.com/sixees/mcp-curl.git
cd mcp-curl && npm install && npm run build
npm start

Tools

curl_execute

Execute HTTP requests with structured parameters. Supports all common HTTP methods, authentication (basic, bearer), headers, form data, redirects, and timeouts.

{
  "url": "https://api.github.com/users/octocat",
  "bearer_token": "ghp_xxx",
  "jq_filter": ".name,.email,.location"
}

Responses exceeding max_result_size (default 500KB) are automatically saved to file. Use jq_filter to extract specific data before the size limit is checked.

jq_query

Query saved JSON files without making new HTTP requests:

{
  "filepath": "/path/to/saved_response.txt",
  "jq_filter": ".users[0:5]"
}

Files must be in the temp directory, MCP_CURL_OUTPUT_DIR, or current working directory.

jq_filter syntax

Syntax

Example

Description

.key

.data

Object property

.[n] or .n

.[0], .0

Array index (non-negative only)

.[n:m]

.[0:10]

Array slice

.["key"]

.["special-key"]

Bracket notation

.a,.b,.c

.name,.email

Multiple paths (returns array)

.key[]

.items[]

Array passthrough (must be last)

This is a path extractor, not jq. The jq expression language — pipes, object construction, and functions (| {id}, map(...), select(...), length) — is not supported and is rejected with an error naming the offending syntax. Iterate-and-project (.items[].id) is rejected too; use an explicit index (.items[0].id) or a slice (.items[0:20]). To reshape or aggregate a response, save it (save_to_file) and post-process it with real jq outside the server.

Programmatic API

Install as a library and build custom MCP servers:

npm install mcp-curl
import { McpCurlServer } from "mcp-curl";

const server = new McpCurlServer()
    .configure({
        baseUrl: "https://api.example.com",
        defaultHeaders: {"Authorization": `Bearer ${process.env.API_TOKEN}`},
        defaultTimeout: 60,
    })
    .beforeRequest((ctx) => {
        console.log(`${ctx.tool}: ${ctx.params.url}`);
    })
    .afterResponse((ctx) => {
        console.log(`Response: ${ctx.response.length} bytes`);
    });

await server.start("stdio");

See the library documentation for the full API reference, including hooks, custom tools, instance utilities, and lifecycle management.

Sanitizing externally-sourced field descriptions

registerCustomTool() sanitizes title, description, and every .describe() string inside inputSchema automatically — recursing through nested z.object(), z.array(), z.union() / z.discriminatedUnion(), z.tuple(), z.record() / z.map(), z.set(), z.intersection(), z.lazy(), .transform() / .pipe(), and through z.optional() / z.default() / z.nullable() / .readonly() / .catch() / z.promise() wrappers. The walker mutates z.globalRegistry in place, preserving every Zod runtime invariant (.refine() / .check() chains, .strict() / .passthrough() modes, array length constraints, factory defaults, ZodDiscriminatedUnion discriminators). You don't need to call sanitizeDescription() manually.

The example below applies sanitizeDescription() defensively at the call site as well — it's optional: registration-time sanitisation already covers every depth. Use it as belt-and-suspenders when wiring untrusted strings (database rows, remote APIs, user-authored YAML) into Zod descriptions.

import { z } from "zod";
import { sanitizeDescription } from "mcp-curl";

// `server` is the McpCurlServer instance from the example above.
const fieldMeta = await fetchFieldDescriptionsFromDb();

server.registerCustomTool(
    "search_records",
    {
        title: "Search records",            // sanitized internally
        description: "Search the catalog.", // sanitized internally
        inputSchema: z.object({
            // sanitizeDescription() here is defensive — registerCustomTool() also
            // sanitises every .describe() string at every depth at registration time.
            q: z.string().describe(sanitizeDescription(fieldMeta.q)),
            limit: z.number().int().min(1).max(100)
                .describe(sanitizeDescription(fieldMeta.limit)),
        }),
    },
    async (params) => { /* handler logic */ }
);

For trusted internal strings, no sanitization is required. See docs/custom-tools.md for the full discussion.

YAML Schema

Define API endpoints declaratively and generate MCP tools:

import { createApiServer } from "mcp-curl";

const server = await createApiServer({
    definitionPath: "./my-api.yaml",
});
await server.start("stdio");
apiVersion: "1.0"
api:
  name: my-api
  baseUrl: https://api.example.com
endpoints:
  - id: list_items
    path: /items
    method: GET
    title: List Items
    description: Get all items
    parameters:
      - name: page
        in: query
        type: integer
        required: false

See YAML Schema Reference for the full specification including authentication, defaults, response filtering, and parameter types.

Fork Workflow

If you fork this repo to build an API-specific server, use the configs/ directory for your definitions:

# 1. Fork and clone
git clone https://github.com/your-org/mcp-curl.git
cd mcp-curl && npm install && npm run build

# 2. Copy the template
cp configs/example.yaml.template configs/my-api.yaml

# 3. Edit your API definition
# See docs/api-schema.md for the full YAML specification

# 4. Create your entry point (configs/*.ts is gitignored)
#    See configs/README.md for a full TypeScript template

# 5. Run your server (using tsx to run the TS file directly)
npx tsx configs/my-api.ts

Files in configs/ matching *.yaml, *.yml, *.ts, *.js are gitignored, so pulling upstream changes (git pull upstream main) won't conflict with your application-specific configuration.

Alternatively, install mcp-curl as an npm dependency in a separate project — see Getting Started.

Security Highlights

  • SSRF protection — blocks private IPs, cloud metadata endpoints, DNS rebinding services, internal TLDs

  • DNS rebinding prevention — DNS resolved before validation, cURL pinned to validated IP via --resolve

  • Protocol whitelist — only http:// and https:// allowed; file://, ftp://, data:, javascript:, etc. blocked at the schema layer (createHttpOnlyUrlSchema), the SSRF layer, and via cURL --proto

  • Host list — allowedHosts names the hosts a request may reach, checked before DNS; a server with a baseUrl defaults to that host alone ("any" opts out)

  • Per-hop redirects — mcp-curl follows redirects itself, one hop at a time; every hop passes the host list, the SSRF check with its own --resolve pin and the rate limit, and a hop to another origin keeps only Accept, Accept-Language, Accept-Encoding, User-Agent and, while the body is kept, its body headers, dropping every other header and the credentials

  • Rate limiting — 60 req/min per host by default (configurable as a sliding window, optionally tightened from the upstream's remaining-count header), 300 req/min per client

  • Local refusals — a request refused for its host, its rate limit or its path, or a redirect hop refused partway through a chain, says so with a code (LOCAL_HOST_NOT_ALLOWED, LOCAL_RATE_LIMITED, LOCAL_REFUSED_PATH, LOCAL_REDIRECT_REFUSED) and no remote-chosen text; an SSRF or DNS refusal of the first request keeps its own message

  • Input validation — Zod schemas, CRLF injection prevention, --data-raw/--form-string to block @ file reads

  • No shell execution — commands spawned via spawn() without shell; allowlist permits only curl

  • File access control — jq_query restricted to temp dir, MCP_CURL_OUTPUT_DIR, and cwd; symlinks resolved

  • Resource limits — 10MB response cap, 100MB global memory, 100ms jq parse timeout, 30s default request timeout, 256 KB HTML/markdown strip cap

  • Secure file permissions — temp dirs 0o700, files 0o600 (owner-only)

  • Localhost port restrictions — when MCP_CURL_ALLOW_LOCALHOST=true, only ports 80, 443, and any port > 1024 are reachable; ports 1–1024 (other than 80/443) stay blocked even with the flag set, to prevent the LLM from reaching SSH (22), SMTP (25), DNS (53), etc.

  • Auth-token validation — MCP_AUTH_TOKEN rejected at HTTP startup if not printable ASCII (0x20–0x7E) or longer than 4096 chars; the rejected token is never echoed in error messages; bearer comparison is timing-safe (crypto.timingSafeEqual over length-padded buffers); the Bearer scheme is matched case-insensitively per RFC 6750 §2.1

  • YAML pre-sanitisation invariant — loadApiSchema(), loadApiSchemaFromString(), validateApiSchema(), AND the directly-re-exported ApiSchemaValidator.parse() all run a single z.preprocess() step that sanitises every user-facing string field before Zod validates structure, so attacker-controlled bidi/zero-width bytes never reach the LLM and never appear in Zod error messages

  • Custom-tool input-schema sanitisation — registerCustomTool() walks inputSchema and sanitises every .describe() string at every depth in place via Zod's globalRegistry (recurses through ZodObject, ZodArray, ZodUnion/ZodDiscriminatedUnion, ZodTuple, ZodRecord/ZodMap, ZodSet, ZodIntersection, ZodPipe, ZodLazy, and through ZodOptional/ZodDefault/ZodNullable/ZodReadonly/ZodCatch/ZodPromise wrappers); all Zod runtime invariants preserved

  • Defence-in-depth response wrap — every tool result (curl_execute, jq_query, YAML endpoints, custom tools, hook short-circuit returns) routes through a single internal post-processor that runs defendText's full pipeline — detect on the original and sanitised text, sanitise, strip markup and markdown beacons, re-detect — on each text part except one that parses as JSON, which is detected on and never rewritten; either kind is then spotlighted when enabled; idempotent via a module-private (non-Symbol.for) tag; fail-open with throttled [wrap-error] log

  • Response sanitisation — Unicode attack chars (bidi overrides, zero-width family, "Sneaky Bits" Variation Selector Supplement, Braille blank, Hangul fillers, Mongolian invisibles, Arabic Letter Mark, …) stripped from non-JSON text responses — a JSON payload is the calling agent's to interpret and is never rewritten; visual-space-padding runs (50+ tabs / NBSP / em-spaces / IDEOGRAPHIC SPACE) and newline runs (20+, with single inline-whitespace interrupters tolerated) collapsed before reaching the LLM; idempotence loop (≤4 iterations) defeats (49 spaces + ZWSP) × N interleaving

  • HTML / Markdown content stripping — <script> and <style> blocks removed from HTML/XHTML/SVG/*+xml responses (ReDoS-hardened with bounded fixed-point stripping, numeric-entity decode inside the loop, 256 KB cap); body-shape sniffer catches markup served under tampered Content-Type; Markdown image beacons and external-URL links replaced with [image removed] / [link removed]; dangerous-scheme URLs (javascript:, vbscript:, file:, data:) blocked in Markdown links and images, including the [![safe](http://x)](javascript:...) nesting case

  • Injection-detection signal — [injection-defense] [hostname] InjectionDetected logged to stderr (throttled 60s per hostname) when a NFKC-normalised regex matches the original response text, its sanitised form (so a phrase split by a zero-width character still matches) or any string token that carries an escape, decoded on its own; observability only — never refuses, redacts, or alters content

Environment Variables

Variable

Description

TRANSPORT

Transport mode: stdio (default) or http

PORT

HTTP transport port (default: 3000)

MCP_AUTH_TOKEN

Bearer token for HTTP transport auth (printable ASCII, ≤4096)

MCP_CURL_OUTPUT_DIR

Default directory for saved responses

MCP_CURL_ALLOW_LOCALHOST

Set true to allow localhost requests

MCP_CURL_HOST

HTTP transport bind address (default: 127.0.0.1)

MCP_CURL_ALLOWED_ORIGINS

Comma-separated origins for HTTP Origin header validation

MCP_CURL_USER_AGENT

Default User-Agent for every request (empty string disables)

MCP_CURL_REFERER

Default Referer for every request (empty string disables)

Documentation

Guide

Description

Library Overview

McpCurlServer class and YAML usage patterns

Getting Started

Step-by-step setup guide

Configuration

All configuration options

Hooks

Request/response interception

Custom Tools

Creating custom MCP tools

YAML Schema Reference

API definition format

Examples

Working example projects in examples/:

MCP Resources & Prompts

  • Resource: curl://docs/api — Built-in API documentation

  • Prompts: api-test (test an endpoint), api-discovery (explore a REST API)

License

MIT

Available Tools

2 tools
curl_executeExecute cURL RequestA

Execute an HTTP request using cURL with structured parameters.

This tool provides a safe, structured way to make HTTP requests with common cURL options. It handles URL encoding, header formatting, and response processing automatically.

Args:

  • url (string, required): The URL to request

  • method (string): HTTP method - GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS

  • headers (object): HTTP headers as key-value pairs

  • data (string): Request body for POST/PUT/PATCH requests

  • form (object): Form data as key-value pairs (multipart/form-data)

  • follow_redirects (boolean): Follow HTTP redirects (default: true)

  • max_redirects (number): Maximum redirects to follow (0-50)

  • insecure (boolean): Skip SSL verification (default: false)

  • timeout (number): Request timeout in seconds (1-300, default: 30)

  • user_agent (string): Custom User-Agent header (a browser-like default is sent automatically if not set; empty string disables)

  • basic_auth (string): Basic auth as "username:password"

  • bearer_token (string): Bearer token for Authorization header

  • verbose (boolean): Include verbose request/response details

  • include_headers (boolean): Include response headers in output

  • compressed (boolean): Request compressed response (default: true)

  • include_metadata (boolean): Wrap response in JSON with metadata

  • jq_filter (string): JSON path filter to extract specific data

  • max_result_size (number): Max bytes to return inline (default: 500KB, max: 1MB). Auto-saves to file when exceeded

  • save_to_file (boolean): Force save response to temp file. Returns filepath instead of content

  • output_dir (string): Custom directory to save files (overrides MCP_CURL_OUTPUT_DIR env var)

jq_filter Syntax:

  • .key - Object property access

  • .[n] or .n - Array index (non-negative only, e.g., .results.0)

  • .[n:m] - Array slice from index n to m

  • .["key"] - Bracket notation for special characters in keys

  • .a,.b,.c - Multiple comma-separated paths (returns array of values, max 20)

jq_filter Validation:

  • Unclosed quotes and brackets throw clear errors

  • Leading zeros in indices rejected (use .0 not .00)

  • Negative indices not supported (unlike real jq)

  • Indices must be within safe integer range

Returns: The HTTP response body, or JSON with metadata if include_metadata is true: { "success": boolean, "exit_code": number, "response": string, "stderr": string (if present), "saved_to_file": boolean (if response was saved), "filepath": string (path to saved file) }

Examples:

Error Handling:

  • Returns error message if cURL fails or times out

  • Exit code 0 indicates success

  • Non-zero exit codes indicate various cURL errors

  • Invalid JSON with jq_filter returns error with response preview

Temp File Lifecycle: Files saved with save_to_file or auto-save are:

  • Stored in a secure temp directory (owner-only access: 0o700/0o600)

  • Deleted on graceful server shutdown (SIGINT/SIGTERM)

  • Orphaned files from crashed sessions are cleaned on next server start

  • Check mcp-curl-* in system temp dir if files persist after crash

Inputs: url (required), method, headers, data, +16 more.

jq_queryQuery JSON FileA
Read-onlyIdempotent

Query an existing JSON file with a jq-like filter expression.

This tool allows you to extract data from saved JSON files without making new HTTP requests. Useful for:

  • Extracting different fields from a large saved response

  • Applying multiple queries to the same data

  • Processing any local JSON file within allowed directories

Args:

  • filepath (string, required): Path to a JSON file to query

  • jq_filter (string, required): JSON path filter expression

  • max_result_size (number): Max bytes inline (default: 500KB, max: 1MB)

  • save_to_file (boolean): Force save result to file

  • output_dir (string): Custom directory to save result files

Filter Syntax:

  • .key - Get object property

  • .[n] - Get array element at index n (non-negative only, also .n with dot notation)

  • .[n:m] - Array slice from n to m

  • .["key"] - Bracket notation for keys with special chars

  • .name,.email - Multiple comma-separated paths (returns array of values, max 20)

  • Note: Negative indices not supported (unlike real jq)

Security:

  • Only files in these directories can be read:

    1. Our temp directory (files saved by curl_execute)

    2. MCP_CURL_OUTPUT_DIR environment variable path

    3. Current working directory and ALL subdirectories (broad - ensure cwd is safe)

  • Maximum file size: 10MB

Examples:

  • Extract name: { "filepath": "/path/to/response.txt", "jq_filter": ".name" }

  • Multiple fields: { "filepath": "/path/to/data.json", "jq_filter": ".name,.email,.id" }

  • Array slice: { "filepath": "/path/to/list.json", "jq_filter": ".items[0:5]" }

Inputs: filepath (required), jq_filter (required), max_result_size, save_to_file, +1 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.5/5.0

    Scored across 2 tools

    Disambiguation5/5

    The two tools have completely distinct purposes: curl_execute handles HTTP requests, while jq_query queries saved JSON files. There is no functional overlap, making selection unambiguous.

    Naming Consistency5/5

    Both tools follow a consistent verb_noun pattern in snake_case (curl_execute, jq_query). The style is uniform, promoting predictability.

    Tool Count3/5

    With only two tools, the server feels minimal for its intended scope. While it covers core HTTP request and JSON querying functionality, additional tools (e.g., manage saved files, list responses) could enhance the surface without overloading it.

    Completeness3/5

    The curl_execute tool is comprehensive for HTTP requests, but the server lacks auxiliary tools such as file management (list, delete saved files) or a way to retrieve response metadata separately. This leaves minor but notable gaps for certain workflows.

    Maintenance

    ActivityMaintained
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      Web Content Retrieval (full webpage, filtered content, or Markdown-converted), Custom User-Agent, Multi-HTTP Method Support (GET/POST/PUT/DELETE/PATCH), LLM-Controlled Request Headers, LLM-Accessible Response Headers, and more.
      3
      7
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides a structured HTTP client tool for making web requests with full HTTP method support, detailed response metadata, and error handling. Enables AI assistants to interact with any web API or endpoint through the curl_request tool.
      2
      MIT
    • A
      license
      A
      quality
      C
      maintenance
      Enables LLMs to make HTTP requests with OAuth2, session cookies, retry logic, and cURL command generation, while providing security features like SSRF protection and TLS enforcement.
      1
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Enables AI agents to send HTTP requests to any endpoint with full control over methods, headers, query parameters, and request bodies.
      1
      MIT