from openai import OpenAI
from mcp.client import Client
async def openai_with_mcp():
# Connect to ShotGrid MCP Server
mcp_client = Client("http://localhost:8000")
# List available tools and convert to OpenAI format
mcp_tools = await mcp_client.list_tools()
openai_tools = [
{
"type": "function",
"function": {
"name": tool.name,
"description": tool.description,
"parameters": tool.parameters
}
}
for tool in mcp_tools
]
# Create OpenAI client
openai_client = OpenAI(api_key="your-api-key")
# Create a chat completion with tools
response = openai_client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant with access to ShotGrid data."},
{"role": "user", "content": "Find all in-progress shots in the Awesome Film project."}
],
tools=openai_tools
)
# Process tool calls
message = response.choices[0].message
for tool_call in message.tool_calls or []:
import json
tool_name = tool_call.function.name
tool_params = json.loads(tool_call.function.arguments)
# Call the MCP tool
tool_result = await mcp_client.call_tool(tool_name, tool_params)
# Send the tool result back to OpenAI
response = openai_client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant with access to ShotGrid data."},
{"role": "user", "content": "Find all in-progress shots in the Awesome Film project."},
{"role": "assistant", "content": message.content, "tool_calls": message.tool_calls},
{"role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(tool_result)}
]
)
print(response.choices[0].message.content)
if __name__ == "__main__":
import asyncio
asyncio.run(openai_with_mcp())