Skip to main content
Glama
ElonJask

ProxyPin MCP Server

by ElonJask

generate_code

Create API call code from captured HTTP requests to simplify client-side implementation and testing.

Instructions

Generate API call code from a captured request.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
request_idYes
languageNopython
frameworkNorequests

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The handler function that implements the logic to generate code for a given request_id, supporting various languages and frameworks.
    @mcp.tool()
    def generate_code(
        request_id: str,
        language: str = "python",
        framework: str = "requests",
    ) -> str:
        """Generate API call code from a captured request."""
        normalized_language = language.lower().strip()
        if normalized_language not in VALID_LANGUAGES:
            return f"# Error: unsupported language '{language}'. Use one of {sorted(VALID_LANGUAGES)}"
    
        request = reader.get_request_by_id(request_id, DetailLevel.FULL)
        if request is None:
            return f"# Error: Request {request_id} not found"
    
        if normalized_language == "curl":
            return request.to_curl()
        if normalized_language == "python":
            normalized_framework = framework.lower().strip()
            if normalized_framework not in VALID_PYTHON_FRAMEWORKS:
                normalized_framework = "requests"
            return _gen_python(request, normalized_framework)
    
        normalized_framework = framework.lower().strip()
        if normalized_framework not in VALID_JS_FRAMEWORKS:
            normalized_framework = "fetch"
        return _gen_js(request, normalized_framework)
  • Helper function to generate Python code for the request.
    def _gen_python(req: RequestFull, framework: str) -> str:
        """Generate Python code."""
        lines = []
        headers = _safe_headers(req)
        method = req.method.upper()
    
        if framework == "httpx":
            lines.extend(["import asyncio", "import httpx", "", "async def main():"])
            indent = "    "
        else:
            lines.extend(["import requests", ""])
            indent = ""
    
        lines.append(f"{indent}method = {json.dumps(method)}")
        lines.append(f"{indent}url = {json.dumps(req.url, ensure_ascii=False)}")
        if headers:
            lines.append(f"{indent}headers = {json.dumps(headers, ensure_ascii=False)}")
    
        payload_param = ""
        if req.request_body_json is not None:
            lines.append(f"{indent}payload = {json.dumps(req.request_body_json, ensure_ascii=False)}")
            payload_param = ", json=payload"
        elif req.request_body:
            lines.append(f"{indent}payload = {json.dumps(req.request_body, ensure_ascii=False)}")
            payload_param = ", data=payload"
    
        headers_param = ", headers=headers" if headers else ""
        lines.append("")
    
        if framework == "httpx":
            lines.append(f"{indent}async with httpx.AsyncClient(timeout=30) as client:")
            lines.append(
                f"{indent}    response = await client.request("
                f"method, url{headers_param}{payload_param})"
            )
            lines.append(f"{indent}    print(response.status_code)")
            lines.append(f"{indent}    print(response.text)")
            lines.append("")
            lines.append("asyncio.run(main())")
        else:
            lines.append(
                f"response = requests.request(method, url{headers_param}{payload_param}, timeout=30)"
            )
            lines.append("print(response.status_code)")
            lines.append("print(response.text)")
    
        return "\n".join(lines)
  • Helper function to generate JavaScript/TypeScript code for the request.
    def _gen_js(req: RequestFull, framework: str) -> str:
        """Generate JavaScript/TypeScript code."""
        lines = []
        headers = _safe_headers(req)
        method = req.method.upper()
    
        if framework == "axios":
            lines.append("import axios from 'axios';")
            lines.append("")
            config: dict[str, Any] = {"method": method, "url": req.url}
            if headers:
                config["headers"] = headers
            if req.request_body_json is not None:
                config["data"] = req.request_body_json
            elif req.request_body:
                config["data"] = req.request_body
    
            lines.append(f"const config = {json.dumps(config, indent=2, ensure_ascii=False)};")
            lines.append("")
            lines.append("axios(config)")
            lines.append("  .then((response) => console.log(response.data))")
            lines.append("  .catch((error) => console.error(error));")
            return "\n".join(lines)
    
        lines.append(f"const url = {json.dumps(req.url, ensure_ascii=False)};")
        options: dict[str, Any] = {"method": method}
        if headers:
            options["headers"] = headers
        lines.append(f"const options = {json.dumps(options, indent=2, ensure_ascii=False)};")
    
        if req.request_body_json is not None:
            lines.append(
                "options.body = JSON.stringify("
                f"{json.dumps(req.request_body_json, ensure_ascii=False)});"
            )
        elif req.request_body:
            lines.append(f"options.body = {json.dumps(req.request_body, ensure_ascii=False)};")
    
        lines.append("")
        lines.append("fetch(url, options)")
        lines.append("  .then((response) => response.text())")
        lines.append("  .then((text) => console.log(text))")
        lines.append("  .catch((error) => console.error('Error:', error));")
        return "\n".join(lines)
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool generates code, implying a read-only or creation operation, but doesn't specify if it requires specific permissions, rate limits, or what the output looks like (though an output schema exists). The description lacks details on error handling, dependencies, or any side effects, leaving significant gaps for a tool that likely involves processing request data.

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 a single, efficient sentence: 'Generate API call code from a captured request.' It is front-loaded with the core purpose and contains no unnecessary words. Every part of the sentence earns its place by specifying the action, resource, and source.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool has 3 parameters with 0% schema coverage, no annotations, and an output schema (which reduces the need to describe return values), the description is minimally adequate. It states what the tool does but lacks details on parameter usage, behavioral traits, and context relative to siblings. For a code-generation tool with multiple inputs, more guidance would improve completeness, but the output schema helps mitigate some gaps.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, meaning none of the parameters (request_id, language, framework) are documented in the schema. The description adds no information about these parameters beyond what's inferred from their names (e.g., 'request_id' likely refers to a captured request). It doesn't explain what values are valid for 'language' or 'framework', or how they affect the generated code, failing to compensate for the low schema coverage.

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 tool's purpose: 'Generate API call code from a captured request.' It specifies the verb ('generate') and resource ('API call code'), and the source ('captured request') provides useful context. However, it doesn't explicitly differentiate from sibling tools like 'analyze_api' or 'get_request', which might involve similar request data.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing a captured request first), exclusions, or comparisons to siblings like 'analyze_api' (which might analyze rather than generate code) or 'get_request' (which might retrieve request details). Usage is implied from the purpose but not explicitly stated.

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/ElonJask/proxypin-mcp'

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