Using mcp-use with OpenAI
The OpenAI adapter allows you to seamlessly integrate tools, resources, and prompts from any MCP server with the OpenAI Python SDK. This enables you to usemcp-use as a comprehensive tool provider for your OpenAI-powered agents.
How it Works
TheOpenAIMCPAdapter converts not only tools but also resources and prompts from your active MCP servers into a format compatible with OpenAI’s tool-calling feature. It maps each of these MCP constructs to a callable function that the OpenAI model can request.
- Tools are converted directly to OpenAI functions.
- Resources are converted into functions that take no arguments and read the resource’s content.
- Prompts are converted into functions that accept the prompt’s arguments.
Step-by-Step Guide
Here’s how to use the adapter to provide MCP tools, resources, and prompts to an OpenAI Chat Completion.Before starting, install the OpenAI SDK:
1
First, set up your
MCPClient with the desired MCP servers. This part of the process is the same as any other mcp-use application.2
Next, instantiate the
OpenAIMCPAdapter. This adapter will be responsible for converting MCP constructs into a format OpenAI can understand.You can pass a
disallowed_tools list to the adapter’s constructor to prevent specific tools, resources, or prompts from being exposed to the model.3
Use the This list will include functions generated from your MCP tools, resources, and prompts.
create_all method on the adapter to inspect all connected MCP servers and generate a list of tools, resources and prompts in the OpenAI function-calling format.If you don’t want to create all tools, you can call single functions. For example, if you only want to use tools and resources, you can do the following:
4
Now, you can use the generated
openai_tools in a call to the OpenAI API. The model will use the descriptions of these tools to decide if it needs to call any of them to answer the user’s query.5
If the model decides to use one or more tools, the The
response_message will contain tool_calls. You need to iterate through these calls, execute the corresponding functions, and append the results to your message history.The OpenAIMCPAdapter makes this easy by providing a tool_executors dictionary and a parse_result method.adapter.parse_result(tool_result) method simplifies the process by correctly formatting the output, whether it’s from a standard tool, a resource, or a prompt.6
Finally, send the updated message history which now includes the tool call results back to the model. This allows the model to use the information gathered from the tools to formulate its final answer.