Gives Me Error When I Am Trying To Use It With An MCP Adapter

by ADMIN 62 views

Introduction

In this article, we will explore the issue of getting a pydantic error when trying to use the codex MCP server with an MCP adapter. We will go through the code snippet, stacktrace error, and provide a solution to resolve the issue.

Code Snippet

The code snippet provided is using the crewai library to create an agent and a task, and then using the mcpadapt library to integrate the codex MCP server with the crew AI code. The code snippet is as follows:

import os
from dotenv import load_dotenv
from crewai import Agent, Crew, Task
from mcp import StdioServerParameters

from mcpadapt.core import MCPAdapt
from mcpadapt.crewai_adapter import CrewAIAdapter

load_dotenv()
if not os.environ.get("OPENAI_API_KEY"):
    raise ValueError("OPENAI_API_KEY must be set in your environment variables")

with MCPAdapt(
    StdioServerParameters(
        command="npx",
        args=["-y", "@codex-data/codex-mcp"],
        env={
        "CODEX_API_KEY": "<api-key>"
      },
    ),
    CrewAIAdapter(),
) as tools:
    agent = Agent(
        role="Research Agent",
        goal="Find studies about hangover",
        backstory="You help find studies about hangover",
        verbose=True,
        tools=[tools[0]],
    )

    task = Task(
        description="Find studies about hangover",
        agent=agent,
        expected_output="A list of studies about hangover",
    )

    crew = Crew(agents=[agent], tasks=[task], verbose=True)
    crew.kickoff()

Stacktrace Error

The stacktrace error provided is as follows:

Traceback (most recent call last):
  File "[...]/python3.13/lib/python3.13/typing.py", line 1035, in __init__
    code = compile(arg_to_compile, '<string>', 'eval')
  File "<string>", line 1
    from
    ^^^^
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "[...]/project/data/crew/mcp_crew.py", line 62, in <module>
    with MCPAdapt(
         ~~~~~~~~^
        StdioServerParameters(
        ^^^^^^^^^^^^^^^^^^^^^^
    ...<6 lines>...
        CustomCrewAIAdapter(),
        ^^^^^^^^^^^^^^^^^^^^^^
    ) as tools:
    ^
  File "[...]/project/.venv/lib/python3.13/site-packages/mcpadapt/core.py", line 256, in __enter__
    return self.tools()
           ~~~~~~~~~~^^
  File "[...]/project/.venv/lib/python3.13/site-packages/mcpadapt/core.py", line 235, in tools
    self.adapter.adapt(partial(_sync_call_tool, session, tool.name), tool)
    ~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "[...]/project/data/crew/mcp_crew.py", line 18, in adapt
    return super().adapt(callback,cp_tool)
           ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
  File "[...]/project/.venv/lib/python3.13/site-packages/mcpadapt/crewai_adapter.py", line 54, in adapt
    ToolInput = create_model_from_json_schema(mcp_tool.inputSchema)
  File "[...]/project/.venv/lib/python3.13/site-packages/mcpadapt/utils/modeling.py", line 148, in create_model_from_json_schema
    root_model = process_schema(model_name, schema)
  File "[...]/project/.venv/lib/python3.13/site-packages/mcpadapt/utils/modeling.py", line 47, in process_schema
    field_type, default = get_field_type(field_name, field_schema, required)
                          ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "[...]/project/.venv/lib/python3.13/site-packages/mcpadapt/utils/modeling.py", line 79, in get_field_type
    process_schema(ref_name, ref_schema)
    ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
  File "[...]/project/.venv/lib/python3.13/site-packages/mcpadapt/utils/modeling.py", line 39, in process_schema
    forward_refs[name] = ForwardRef(name)
                         ~~~~~~~~~~^^^^^^
  File "[...]/python3.13/lib/python3.13/typing.py", line 1037, in __init__
    raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
SyntaxError: Forward reference must be an expression -- got 'from'

Solution

The issue is caused by a forward reference in the mcpadapt library. The create_model_from_json_schema function is trying to create a model from a JSON schema, but the schema contains a forward reference to a type that is not defined.

To resolve this issue, we need to update the mcpadapt library to handle forward references correctly. We can do this by adding a check in the process_schema function to see if the reference is a forward reference, and if so, create a new model for it.

Here is the updated code for the process_schema function:

def process_schema(model_name, schema):
    forward_refs = {}
    for field_name, field_schema in schema.items():
        field_type, default = get_field_type(field_name, field_schema, required)
        if field_type == "forward_ref":
            ref_name = field_schema["ref"]
            if ref_name not in forward_refs:
                forward_refs[ref_name] = ForwardRef(ref_name)
            field_type = forward_refs[ref_name]
        # ... rest of the function remains the same ...

Conclusion

In this article, we explored the issue of getting a pydantic error when trying to use the codex MCP server with an MCP adapter. We went through the code snippet, stacktrace error, and provided a solution to resolve the issue. The solution involves updating the mcpadapt library to handle forward references correctly.

Additional Information

  • The mcpadapt library is a Python library that provides a way to integrate the codex MCP server with other AI frameworks.
  • The crewai library is a Python library that provides a way to create and manage AI agents and tasks.
  • The codex library is a Python library that provides a way to interact with the codex MCP server.

References

Q: What is the issue with using the codex MCP server with an MCP adapter?

A: The issue is caused by a forward reference in the mcpadapt library. The create_model_from_json_schema function is trying to create a model from a JSON schema, but the schema contains a forward reference to a type that is not defined.

Q: What is a forward reference?

A: A forward reference is a reference to a type that has not been defined yet. In the context of the mcpadapt library, a forward reference is a reference to a type that is defined in a different module or file.

Q: How do I fix the issue?

A: To fix the issue, you need to update the mcpadapt library to handle forward references correctly. You can do this by adding a check in the process_schema function to see if the reference is a forward reference, and if so, create a new model for it.

Q: What is the updated code for the process_schema function?

A: The updated code for the process_schema function is as follows:

def process_schema(model_name, schema):
    forward_refs = {}
    for field_name, field_schema in schema.items():
        field_type, default = get_field_type(field_name, field_schema, required)
        if field_type == "forward_ref":
            ref_name = field_schema["ref"]
            if ref_name not in forward_refs:
                forward_refs[ref_name] = ForwardRef(ref_name)
            field_type = forward_refs[ref_name]
        # ... rest of the function remains the same ...

Q: What are the benefits of using the codex MCP server with an MCP adapter?

A: The benefits of using the codex MCP server with an MCP adapter include:

  • Improved performance: The MCP adapter provides a way to integrate the codex MCP server with other AI frameworks, which can improve the performance of your AI applications.
  • Increased flexibility: The MCP adapter provides a way to customize the behavior of the codex MCP server, which can increase the flexibility of your AI applications.
  • Better support: The MCP adapter provides a way to get better support for the codex MCP server, which can help you to resolve issues and improve your AI applications.

Q: What are the limitations of using the codex MCP server with an MCP adapter?

A: The limitations of using the codex MCP server with an MCP adapter include:

  • Complexity: The MCP adapter can add complexity to your AI applications, which can make them harder to understand and maintain.
  • Dependence on the MCP adapter: Your AI applications may become dependent on the MCP adapter, which can make them harder to maintain and update.
  • Limited support: The MCP adapter may not provide the same level of support as the codex MCP server, which can make it harder to resolve issues.

Q: How do I get started with using the codex MCP server with an MCP adapter?

A: To get started with using codex MCP server with an MCP adapter, you need to:

  • Install the MCP adapter: You need to install the MCP adapter using pip or another package manager.
  • Import the MCP adapter: You need to import the MCP adapter in your Python code.
  • Configure the MCP adapter: You need to configure the MCP adapter to work with the codex MCP server.
  • Use the MCP adapter: You need to use the MCP adapter to integrate the codex MCP server with your AI applications.

Q: What are the best practices for using the codex MCP server with an MCP adapter?

A: The best practices for using the codex MCP server with an MCP adapter include:

  • Follow the documentation: You need to follow the documentation for the MCP adapter and the codex MCP server to ensure that you are using them correctly.
  • Test your code: You need to test your code thoroughly to ensure that it is working correctly with the MCP adapter and the codex MCP server.
  • Monitor your performance: You need to monitor your performance to ensure that the MCP adapter and the codex MCP server are working correctly and efficiently.
  • Update your code regularly: You need to update your code regularly to ensure that you are using the latest version of the MCP adapter and the codex MCP server.