Skip to content

fixes issue 39 #40

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,7 @@ wheels/
notebooks/

# mkdocs documentation
/site
/site

# macOS files
.DS_Store
8 changes: 7 additions & 1 deletion src/mcpadapt/crewai_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
from pydantic import BaseModel

from mcpadapt.core import ToolAdapter
from mcpadapt.utils.modeling import create_model_from_json_schema
from mcpadapt.utils.modeling import (
create_model_from_json_schema,
resolve_refs_and_remove_defs
)

json_type_mapping: dict[str, Type] = {
"string": str,
Expand Down Expand Up @@ -51,6 +54,9 @@ def adapt(
Returns:
A CrewAI tool.
"""
mcp_tool.inputSchema = resolve_refs_and_remove_defs(
mcp_tool.inputSchema
)
ToolInput = create_model_from_json_schema(mcp_tool.inputSchema)

class CrewAIMCPTool(BaseTool):
Expand Down
34 changes: 33 additions & 1 deletion src/mcpadapt/utils/modeling.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from copy import deepcopy
from typing import Any, Dict, ForwardRef, List, Optional, Type, Union

from pydantic import BaseModel, Field, create_model
import re

json_type_mapping: dict[str, Type] = {
"string": str,
Expand All @@ -21,6 +22,33 @@
}


def resolve_refs_and_remove_defs(json_obj):
# Extract $defs
defs = json_obj.get("$defs", {})

# Function to recursively resolve $ref
def _resolve(obj):
if isinstance(obj, dict):
if "$ref" in obj:
ref_path = obj["$ref"]
match = re.match(r"#/\$defs/(\w+)", ref_path)
if match:
def_key = match.group(1)
return _resolve(deepcopy(defs.get(def_key, {})))
return {k: _resolve(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [_resolve(i) for i in obj]
else:
return obj

json_obj = _resolve(json_obj)

# Remove $defs
json_obj.pop("$defs", None)

return json_obj


def create_model_from_json_schema(
schema: dict[str, Any], model_name: str = "DynamicModel"
) -> Type[BaseModel]:
Expand Down Expand Up @@ -51,6 +79,10 @@ def process_schema(name: str, schema_def: Dict[str, Any]) -> Type[BaseModel]:
default=default,
description=field_schema.get("description", ""),
title=field_schema.get("title", ""),
items=field_schema.get("items", None),
anyOf=field_schema.get("anyOf", []),
enum=field_schema.get("enum", None),
properties=field_schema.get("properties", {}),
),
)

Expand Down
131 changes: 131 additions & 0 deletions tests/test_crewai_adapter.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import ast
import re

from textwrap import dedent

import pytest
Expand All @@ -7,6 +10,22 @@
from mcpadapt.crewai_adapter import CrewAIAdapter


def extract_and_eval_dict(text):
# Match the first outermost curly brace block
match = re.search(r'\{.*\}', text, re.DOTALL)
if not match:
raise ValueError("No dictionary-like structure found in the string.")

dict_str = match.group(0)

try:
# Safer than eval for parsing literals
parsed_dict = ast.literal_eval(dict_str)
return parsed_dict
except Exception as e:
raise ValueError(f"Failed to evaluate dictionary: {e}")


@pytest.fixture
def echo_server_script():
return dedent(
Expand All @@ -25,6 +44,60 @@ def echo_tool(text: str) -> str:
)


@pytest.fixture
def custom_script_with_custom_arguments():
return dedent(
'''
from mcp.server.fastmcp import FastMCP
from typing import Literal
from enum import Enum
from pydantic import BaseModel

class Animal(BaseModel):
legs: int
name: str

mcp = FastMCP("Server")

@mcp.tool()
def custom_tool(
text: Literal["ciao", "hello"],
animal: Animal,
env: str | None = None,

) -> str:
pass

mcp.run()
'''
)


@pytest.fixture
def custom_script_with_custom_list():
return dedent(
'''
from mcp.server.fastmcp import FastMCP
from pydantic import BaseModel

class Point(BaseModel):
x: float
y: float

mcp = FastMCP("Server")

@mcp.tool()
def custom_tool(
points: list[Point],

) -> str:
pass

mcp.run()
'''
)


@pytest.fixture
def echo_server_sse_script():
return dedent(
Expand Down Expand Up @@ -108,6 +181,64 @@ def test_basic_sync(echo_server_script):
assert tools[0].run(text="hello") == "Echo: hello"


# Fails if enums, unions, or pydantic classes are not included in the
# generated schema
def test_basic_sync_custom_arguments(custom_script_with_custom_arguments):
with MCPAdapt(
StdioServerParameters(
command="uv",
args=[
"run",
"python",
"-c",
custom_script_with_custom_arguments
]
),
CrewAIAdapter(),
) as tools:
tools_dict = extract_and_eval_dict(tools[0].description)
assert tools_dict != {}
assert tools_dict["properties"] != {}
# Enum tests
assert "enum" in tools_dict["properties"]["text"]
assert "hello" in tools_dict["properties"]["text"]["enum"]
assert "ciao" in tools_dict["properties"]["text"]["enum"]
# Pydantic class tests
assert tools_dict["properties"]["animal"]["properties"] != {}
assert tools_dict["properties"]["animal"]["properties"]["legs"] != {}
assert tools_dict["properties"]["animal"]["properties"]["name"] != {}
# Union tests
assert "anyOf" in tools_dict["properties"]["env"]
assert tools_dict["properties"]["env"]["anyOf"] != []
types = [
opt.get("type") for opt in tools_dict["properties"]["env"]["anyOf"]
]
assert "null" in types
assert "string" in types

# Raises KeyError
# if the pydantic objects list is not correctly resolved with $ref handling
# within mcp_tool.inputSchema
def test_basic_sync_custom_list(custom_script_with_custom_list):
with MCPAdapt(
StdioServerParameters(
command="uv",
args=[
"run",
"python",
"-c",
custom_script_with_custom_list
]
),
CrewAIAdapter(),
) as tools:
tools_dict = extract_and_eval_dict(tools[0].description)
assert tools_dict != {}
assert tools_dict["properties"] != {}
# Pydantic class tests
assert tools_dict["properties"]["points"]["items"] != {}


def test_basic_sync_sse(echo_sse_server):
sse_serverparams = echo_sse_server
with MCPAdapt(
Expand Down
44 changes: 15 additions & 29 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.