Skip to content

Create MCP proxy from OpenAPI specifications #1561

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 61 commits into from
May 12, 2025

Conversation

sternakt
Copy link
Collaborator

@sternakt sternakt commented Apr 7, 2025

Description:
We need a tool that automatically generates an stdio-based MCP server from an OpenAPI specification (either through a URL or as a JSON file). This server will connect to the service described in the OpenAPI spec and expose it as an MCP tool. The main goal is to enable easy creation of authenticated MCP tools for any service that has an OpenAPI specification, including the handling of authentication and security mechanisms as specified by the OpenAPI standard.

Key Features & Requirements:

  • Input:

    • The tool should accept either a URL or a JSON file as input, containing the OpenAPI specification.
    • A path to a folder where to export generated files
  • Output:

    • Files generated in the given folder.
    • Generate a stdio-based MCP server that translates the API described in the OpenAPI spec into an MCP tool.
    • The server should support the API operations defined in the OpenAPI specification and provide a standard interface for interacting with them via MCP.
  • Authentication and Security:

    • The tool should handle the authentication and security mechanisms defined in the OpenAPI specification (e.g., OAuth2, API keys).
    • Secrets (API keys, OAuth credentials, etc.) will be passed to the stdio-based MCP server via environment variables. The tool must support securely retrieving these secrets from environment variables, in alignment with the OpenAPI security schemes (such as API keys or OAuth tokens).
    • The generated MCP server should map the authentication methods described in the OpenAPI spec to the standard ways supported by the MCP specification, using these environment variables.
  • MCP Server:

    • The generated MCP server should run over stdio (standard input and output) to interact with external services via a text-based interface.
    • The server must communicate with the service described in the OpenAPI specification using the methods and authentication schemes defined in the specification, with secrets securely passed via environment variables.
  • Error Handling:

    • The generated MCP tool should provide robust error handling and clear error messages when interacting with the service.
    • Specifically, errors related to authentication failures (e.g., missing or invalid environment variables) should be clearly indicated.
  • Environment Variables:

    • The tool must allow users to set relevant secrets (such as API keys or OAuth tokens) as environment variables.
    • The tool should read these environment variables to authenticate requests and interact with the service described by the OpenAPI specification.
  • Use Case:

    • This tool is meant to allow easy conversion of OpenAPI specifications into an MCP server, enabling any API described by an OpenAPI document to be directly usable as an MCP tool.
    • The use of stdio allows the generated MCP tool to interact seamlessly with other applications, scripts, and agents that support the MCP format.
    • The use of environment variables for secrets adds a layer of security and ensures best practices for managing sensitive data.

Motivation:

  • OpenAPI specifications are widely available for modern APIs, and this tool would automate the process of creating an MCP server that can serve those APIs in a standardized way.
  • By handling authentication and security according to the OpenAPI spec, and by using environment variables for secrets, it ensures that the resulting MCP tools follow common and widely accepted practices, making it easy to integrate and maintain them in enterprise environments.

Acceptance Criteria:

  • A working tool that takes an OpenAPI URL or JSON as input.
  • The tool generates an MCP server running over stdio that:
    • Supports all API operations defined in the OpenAPI spec.
    • Handles authentication and security mechanisms as defined in the spec (e.g., OAuth2, API keys).
    • Accepts secrets through environment variables for authentication.
    • Outputs responses in the MCP format, adhering to the protocol’s requirements.
    • Provides appropriate error handling for issues such as missing or invalid environment variables for authentication.

Example Code:

The following Python example demonstrates how to generate an MCP server from an OpenAPI specification, authenticate using environment variables, and interact with the API through an LLM agent:

from pathlib import Path
from mcp import ClientSession, StdioServerParameters
from mcp.client.sse import sse_client
from mcp.client.stdio import stdio_client
from autogen import LLMConfig
from autogen.agentchat import AssistantAgent
from autogen.mcp import create_toolkit
from autogen.mcp.mcp_proxy import MCPProxy

client_source_path = Path(...)

# Create an MCP Proxy server based on the OpenAPI specification
MCPProxy.create(
    openapi_url="https://dev.infobip.com/openapi/products/whatsapp.json",  # OpenAPI spec URL
    client_source_path=client_source_path,  # Path to the generated client source
    servers=[{"url": "https://api.infobip.com"}],  # List of servers to connect to
)

async def create_toolkit_and_run(session: ClientSession) -> None:
    # Create a toolkit with available MCP tools
    toolkit = await create_toolkit(session=session)
    
    # Initialize an AssistantAgent with GPT-4o-mini model
    agent = AssistantAgent(name="assistant", llm_config=LLMConfig(model="gpt-4o-mini", api_type="openai"))
    
    # Register the toolkit with the agent
    toolkit.register_for_llm(agent)

    # Make a request using the MCP tool
    result = await agent.a_run(
        message="Add 123223 and 456789",  # Example message for the tool
        tools=toolkit.tools,
        max_turns=2,
        user_input=False,
    )
    await result.process()

# Create server parameters for stdio connection, including environment variables for secrets
server_params = StdioServerParameters(
    command="python",  # The command to run the server
    args=[
        str(tmp_path / "main_tmp.py"),  # Path to the server script
        "stdio",  # Stdio transport mode
    ],
    env={
        "API_KEY": "your-api-key",  # Example API Key passed as an environment variable
        "OAUTH2_TOKEN": "your-oauth2-token",  # Example OAuth2 token passed as an environment variable
    },
)

# Initialize the stdio connection and create the MCP server session
async with stdio_client(server_params) as (read, write), ClientSession(read, write) as session:
    await session.initialize()  # Initialize the session
    await create_toolkit_and_run(session)  # Run the toolkit and agent

Explanation:

  1. MCPProxy.create():

    • This method creates an MCP proxy server based on an OpenAPI specification, connecting to the service described in the spec.
    • You need to provide the OpenAPI URL and the client source path.
  2. create_toolkit_and_run():

    • This function creates a toolkit using the MCP session and registers an LLM agent (AssistantAgent), which can use the MCP tools.
    • The agent can make requests using the available tools.
  3. Environment Variables:

    • Authentication secrets like API_KEY and OAUTH2_TOKEN are passed as environment variables to the stdio_client. The server uses these variables to authenticate with the service.
  4. Stdio Connection:

    • The connection is established using stdio_client, which communicates with the server through standard input and output.
    • The ClientSession manages the session between the MCP server and the agent.

Additional Notes:

  • The tool should clearly document which environment variables are required (e.g., API_KEY, OAUTH2_TOKEN).
  • Consider the inclusion of any necessary libraries for API requests, such as requests or httpx, to facilitate communication with the service described in the OpenAPI specification.
  • The generated code should be easily extendable to handle more complex use cases or API specifications.

@sternakt sternakt linked an issue Apr 7, 2025 that may be closed by this pull request
@davorrunje davorrunje changed the title 1554 create mcp proxy from openapi specifications Create MCP proxy from OpenAPI specifications Apr 7, 2025
@davorrunje davorrunje self-assigned this Apr 7, 2025
@davorrunje davorrunje self-requested a review April 7, 2025 12:27
@davorrunje davorrunje marked this pull request as ready for review May 2, 2025 08:52
@davorrunje davorrunje marked this pull request as draft May 2, 2025 11:18
@davorrunje davorrunje marked this pull request as ready for review May 12, 2025 10:35
@davorrunje davorrunje added this pull request to the merge queue May 12, 2025
Merged via the queue into main with commit 8dc3b3a May 12, 2025
17 checks passed
@davorrunje davorrunje deleted the 1554-create-mcp-proxy-from-openapi-specifications branch May 12, 2025 11:00
Copy link

codecov bot commented May 12, 2025

Codecov Report

Attention: Patch coverage is 35.25469% with 483 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
autogen/mcp/mcp_proxy/mcp_proxy.py 22.71% 244 Missing and 1 partial ⚠️
autogen/mcp/mcp_proxy/security.py 56.83% 77 Missing and 2 partials ⚠️
autogen/mcp/mcp_proxy/operation_grouping.py 34.66% 49 Missing ⚠️
...ogen/mcp/mcp_proxy/patch_fastapi_code_generator.py 25.92% 40 Missing ⚠️
autogen/mcp/mcp_proxy/operation_renaming.py 32.50% 27 Missing ⚠️
...en/mcp/mcp_proxy/fastapi_code_generator_helpers.py 34.37% 21 Missing ⚠️
autogen/mcp/mcp_proxy/security_schema_visitor.py 35.00% 13 Missing ⚠️
autogen/mcp/__main__.py 66.66% 5 Missing and 1 partial ⚠️
autogen/mcp/mcp_proxy/__init__.py 57.14% 2 Missing and 1 partial ⚠️

❗ There is a different number of reports uploaded between BASE (78f6959) and HEAD (41febb9). Click for more details.

HEAD has 1428 uploads less than BASE
Flag BASE (78f6959) HEAD (41febb9)
3.10 108 0
ubuntu-latest 165 1
commsagent-discord 9 0
optional-deps 174 0
3.9 92 0
3.13 91 0
commsagent-slack 9 0
browser-use 7 0
macos-latest 114 0
core-without-llm 14 1
3.11 76 1
3.12 36 0
windows-latest 124 0
commsagent-telegram 9 0
graph-rag-falkor-db 6 0
jupyter-executor 9 0
interop 13 0
interop-langchain 9 0
retrievechat-qdrant 14 0
retrievechat-pgvector 10 0
mcp 13 0
rag 7 0
crawl4ai 13 0
retrievechat-mongodb 10 0
retrievechat 15 0
interop-pydantic-ai 8 0
docs 6 0
interop-crewai 9 0
websockets 9 0
google-api 13 0
twilio 9 0
mistral 14 0
gpt-assistant-agent 3 0
wikipedia-api 13 0
agent-eval 1 0
llama-index-agent 3 0
retrievechat-couchbase 3 0
together 14 0
teachable 4 0
long-context 3 0
gemini 14 0
anthropic 16 0
cerebras 15 0
groq 14 0
websurfer 15 0
ollama 15 0
cohere 15 0
bedrock 15 0
swarm 14 0
integration 24 0
falkordb 2 0
core-llm 6 0
neo4j 2 0
captainagent 1 0
autobuild 1 0
lmm 1 0
deepseek 1 0
openai 1 0
Files with missing lines Coverage Δ
autogen/mcp/mcp_proxy/__init__.py 57.14% <57.14%> (ø)
autogen/mcp/__main__.py 66.66% <66.66%> (ø)
autogen/mcp/mcp_proxy/security_schema_visitor.py 35.00% <35.00%> (ø)
...en/mcp/mcp_proxy/fastapi_code_generator_helpers.py 34.37% <34.37%> (ø)
autogen/mcp/mcp_proxy/operation_renaming.py 32.50% <32.50%> (ø)
...ogen/mcp/mcp_proxy/patch_fastapi_code_generator.py 25.92% <25.92%> (ø)
autogen/mcp/mcp_proxy/operation_grouping.py 34.66% <34.66%> (ø)
autogen/mcp/mcp_proxy/security.py 56.83% <56.83%> (ø)
autogen/mcp/mcp_proxy/mcp_proxy.py 22.71% <22.71%> (ø)

... and 73 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

karikalanarun pushed a commit to karikalanarun/ag2 that referenced this pull request Jun 11, 2025
* Init mcp proxy cli

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* Fix ForwardRef issues by removing from __future__ import annotations

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* Add security examples, update version

* Add security examples, update version

* version updated

* version updated to 0.8.6alpha2

* WIP

* Trello WIP

* Polish

* Fix template

* 1652 add operation renaming using llm (ag2ai#1659)

* WIP

* Add operation renaming

* version updated to 0.8.8alpha0

* WIP

* Fix function renaming

* version updated to 0.8.8alpha1

* Add schema configuration examples to security examples

* Add operation grouping

* stringcase added to dependancies

* Remove stringcase from imports

* Remove stringcase from imports

* Move fastapi_code_generator to optional import

* Move fastapi_code_generator to optional import

* Move fastapi_code_generator to optional import

* Remove entrypoint for MCP CLI

* Add configuration type to MCPProxy.create

* Add configuration type to MCPProxy.create

* Fix version

* Patch generation failure when components are missing from api specification

* Prepare for prerelease

* Example cleanup

* Add mcp-proxy-gen as dependency in notebooks

* linting

* Add requirement decorator

* Rearrange decorator

---------

Co-authored-by: Davor Runje <[email protected]>
Co-authored-by: Davor Runje <[email protected]>
Co-authored-by: Kumaran Rajendhiran <[email protected]>
Co-authored-by: Kumaran Rajendhiran <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[EPIC] Create MCP proxy from OpenAPI specifications
3 participants