mirror of
https://github.com/mcp-use/mcp-use.git
synced 2026-09-14 18:06:01 +08:00
8348c59a53
* docs: reorganize navigation and clean up content - Remove 'Misc' group with misplaced blog posts - Remove 'Libraries' redirect group from Home nav - Simplify 'Dev Tools' group (flatten Inspector, CLI, Tunneling) - Remove individual changelog versions from Python nav (keep summary) - Remove changelog from TypeScript 'Get Started' group - Remove tunneling duplicate from Python Development group - Rewrite mcp101 as clean MCP concepts page (was pitch deck) - Delete typescript/blog posts (not technical docs) - Add redirects for deleted blog post URLs * docs: fix content accuracy and remove sloppy language - Fix broken python/server/mcp-apps link in home page - Remove informal pitch-speak from python/server/index.mdx - Fix grammar error in typescript/server/index.mdx - Update typescript/client/logging.mdx: remove fake 'coming soon' API code - Fix non-existent model name gpt-5.1 in typescript quickstart - Fix mcp_use naming in development contributing guide * docs: fix incorrect TypeScript server API calls in inspector docs - Replace server.addTool() with server.tool() (correct mcp-use API) - Add missing zod import to debugging-chatgpt-apps example * docs: fix fake model names (gpt-5.1 → gpt-4o) in agent docs * docs: update model names, fix APIs, and add agent visibility hints - Replace all deprecated model names with latest: gpt-4.1, gpt-4.1-mini, claude-sonnet-4-6, claude-opus-4-7, gemini-2.5-flash across all docs - Fix TypeScript server.tool() API in installation.mdx (old positional string form) - Fix TypeScript agent.run() in quickstart.mdx (deprecated string form → object) - Remove broken manufact.com/docs/llms.txt hidden hints from 5 pages - Add <Visibility for="agents"> block to mcp101.mdx with install commands, key classes, and API signatures for agent-oriented navigation - Add LangChain provider install note to Python quickstart (mcp-use agent requires a separate langchain-* provider package) - Update model name cards in Python llm-integration.mdx * docs: clean up remaining stale model names and improve accuracy - Update supported model lists in Python and TypeScript llm-integration pages - Fix cost optimization table to use current model IDs - Update TypeScript agent overview supported providers list * docs: add LangChain provider install to TypeScript quickstart agent section The MCPAgent requires a separate @langchain/* provider package; this was not mentioned before the code example that imports from @langchain/openai. * docs: update to latest flagship model IDs (May 2026) - OpenAI: gpt-4.1 → gpt-5.5, gpt-4.1-mini → gpt-5.5-mini - Google: gemini-2.5-flash → gemini-3.1-flash, gemini-2.5-pro → gemini-3.1-pro - Groq: llama-3.1-* → llama-4-scout-17b-16e-instruct - Anthropic (claude-opus-4-7, claude-sonnet-4-6) already current, no change * docs: replace all em dashes with hyphens * docs: restore llms.txt hints using Visibility component * docs: simplify TypeScript logging page to unsupported notice only * docs: rewrite mcp101 to explain MCP protocol with mcp-use examples and doc links * docs: remove goal.md * docs: revert nav changes, keep only Misc group removal and blog redirects * docs: reorder mcp101 to Server/App -> Client/Inspector -> Agent, restore title * docs: add code examples for Resources and Prompts in mcp101 * docs: remove em dashes from mcp101 * docs: add MCPClient code examples to mcp101 * docs: add React client example to mcp101 * docs: add agent code examples to mcp101 * docs: expand MCP Apps section in mcp101 with example and links * docs: restore Contacts, Socials, and Founders sections to mcp101 * docs: add context-setting intro paragraph to mcp101 for new readers * docs: add MCP stores section to mcp101 intro with Claude, ChatGPT, Cursor * docs: fix Claude store link * docs: fix ChatGPT store link * docs: fix Cursor store link * docs: replace store Cards with linked image grid * docs: add captions to store images * docs: add Notifications to client primitives table in mcp101 * docs: add lead-in paragraph before resource cards at bottom of mcp101 * docs: move resource cards to end of page after Contacts/Socials/Founders * docs: demote Contacts/Socials/Founders to bold text to remove from TOC * docs: move Contacts/Socials/Founders to very end of mcp101 * docs: add Resources and Contacts section headers, link official MCP docs * chore(docs): update site metadata, footer links, and rename mcp_use to mcp-use * update docs metadata + images * docs: enhance MCP section by highlighting the reach of MCP stores with 1 billion weekly active users * api ref
271 lines
10 KiB
Plaintext
271 lines
10 KiB
Plaintext
---
|
||
title: "OpenAI"
|
||
description: "Use mcp-use tools, resources, and prompts directly with the OpenAI SDK"
|
||
tag: "New"
|
||
icon: "/images/openai.svg"
|
||
---
|
||
|
||
# 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 use `mcp-use` as a comprehensive tool provider for your OpenAI-powered agents.
|
||
|
||
## How it Works
|
||
|
||
The `OpenAIMCPAdapter` 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.
|
||
|
||
The adapter maintains a mapping of these generated functions to their actual execution logic, allowing you to easily call them when requested by the model.
|
||
|
||
## Step-by-Step Guide
|
||
|
||
Here's how to use the adapter to provide MCP tools, resources, and prompts to an OpenAI Chat Completion.
|
||
|
||
<Note>
|
||
Before starting, install the OpenAI SDK:
|
||
```bash
|
||
uv pip install openai
|
||
```
|
||
</Note>
|
||
|
||
<Steps>
|
||
<Step name="Initialize MCPClient">
|
||
First, set up your `MCPClient` with the desired MCP servers. This part of the process is the same as any other `mcp-use` application.
|
||
|
||
```python
|
||
from mcp_use import MCPClient
|
||
|
||
config = {
|
||
"mcpServers": {
|
||
"airbnb": {"command": "npx", "args": ["-y", "@openbnb/mcp-server-airbnb", "--ignore-robots-txt"]},
|
||
}
|
||
}
|
||
|
||
client = MCPClient(config=config)
|
||
```
|
||
</Step>
|
||
|
||
<Step name="Create the OpenAI Adapter">
|
||
Next, instantiate the `OpenAIMCPAdapter`. This adapter will be responsible for converting MCP constructs into a format OpenAI can understand.
|
||
|
||
```python
|
||
from mcp_use.agents.adapters import OpenAIMCPAdapter
|
||
|
||
# Creates the adapter for OpenAI's format
|
||
adapter = OpenAIMCPAdapter()
|
||
```
|
||
<Tip>
|
||
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.
|
||
</Tip>
|
||
</Step>
|
||
|
||
<Step name="Generate OpenAI-Compatible Tools">
|
||
Use the `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.
|
||
|
||
```python
|
||
# Convert tools from active connectors to the OpenAI's format
|
||
# this will populates the list of tools, resources and prompts
|
||
await adapter.create_all(client)
|
||
|
||
# If you decided to create all tools (list concatenation)
|
||
openai_tools = adapter.tools + adapter.resources + adapter.prompts
|
||
```
|
||
|
||
This list will include functions generated from your MCP tools, resources, and prompts.
|
||
|
||
<Tip>
|
||
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:
|
||
|
||
```python
|
||
await adapter.create_tools(client)
|
||
await adapter.create_resources(client)
|
||
|
||
# Then, you can decide which ones to use:
|
||
openai_tools = adapter.tools + adapter.resources
|
||
```
|
||
</Tip>
|
||
</Step>
|
||
|
||
<Step name="Make the Initial API Call">
|
||
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.
|
||
|
||
```python
|
||
from openai import OpenAI
|
||
|
||
openai = OpenAI()
|
||
messages = [
|
||
{"role": "user", "content": "Please tell me the cheapest hotel for two people in Trapani."}
|
||
]
|
||
|
||
response = openai.chat.completions.create(
|
||
model="gpt-5.5",
|
||
messages=messages,
|
||
tools=openai_tools
|
||
)
|
||
|
||
response_message = response.choices[0].message
|
||
messages.append(response_message)
|
||
```
|
||
</Step>
|
||
|
||
<Step name="Execute Tool Calls">
|
||
If the model decides to use one or more tools, 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.
|
||
|
||
```python
|
||
# Handle the tool calls (Tools, Resources, Prompts...)
|
||
for tool_call in response_message.tool_calls:
|
||
import json
|
||
|
||
function_name = tool_call.function.name
|
||
arguments = json.loads(tool_call.function.arguments)
|
||
|
||
# 1. Use the adapter's map to get the correct executor
|
||
executor = adapter.tool_executors.get(function_name)
|
||
|
||
if not executor:
|
||
content = f"Error: Tool '{function_name}' not found."
|
||
else:
|
||
try:
|
||
# 2. Execute the tool using the retrieved function
|
||
print(f"Executing tool: {function_name}({arguments})")
|
||
tool_result = await executor(**arguments)
|
||
|
||
# 3. Use the adapter's universal parser
|
||
content = adapter.parse_result(tool_result)
|
||
except Exception as e:
|
||
content = f"Error executing tool: {e}"
|
||
|
||
# 4. Append the result for this specific tool call
|
||
messages.append(
|
||
{
|
||
"tool_call_id": tool_call.id,
|
||
"role": "tool",
|
||
"name": function_name,
|
||
"content": content
|
||
}
|
||
)
|
||
```
|
||
The `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.
|
||
</Step>
|
||
|
||
<Step name="Get the Final Response">
|
||
|
||
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.
|
||
|
||
```python
|
||
second_response = openai.chat.completions.create(
|
||
model="gpt-5.5",
|
||
messages=messages,
|
||
tools=openai_tools
|
||
)
|
||
|
||
final_message = second_response.choices[0].message
|
||
print("\n--- Final response from the model ---")
|
||
print(final_message.content)
|
||
```
|
||
</Step>
|
||
</Steps>
|
||
|
||
## Complete Example
|
||
|
||
For reference, here is the complete, runnable code for integrating mcp-use with the OpenAI SDK.
|
||
|
||
```python
|
||
import asyncio
|
||
|
||
from dotenv import load_dotenv
|
||
from openai import OpenAI
|
||
|
||
from mcp_use import MCPClient
|
||
from mcp_use.agents.adapters import OpenAIMCPAdapter
|
||
|
||
# This example demonstrates how to use our integration
|
||
# adapters to use MCP tools and convert to the right format.
|
||
# In particularly, this example uses the OpenAIMCPAdapter.
|
||
|
||
load_dotenv()
|
||
|
||
|
||
async def main():
|
||
config = {
|
||
"mcpServers": {
|
||
"airbnb": {"command": "npx", "args": ["-y", "@openbnb/mcp-server-airbnb", "--ignore-robots-txt"]},
|
||
}
|
||
}
|
||
|
||
try:
|
||
client = MCPClient(config=config)
|
||
|
||
# Creates the adapter for OpenAI's format
|
||
adapter = OpenAIMCPAdapter()
|
||
|
||
# Convert tools from active connectors to the OpenAI's format
|
||
# this will populates the list of tools, resources and prompts
|
||
await adapter.create_all(client)
|
||
|
||
# If you don't want to create all tools, you can call single functions
|
||
# await adapter.create_tools(client)
|
||
# await adapter.create_resources(client)
|
||
# await adapter.create_prompts(client)
|
||
|
||
# If you decided to create all tools (list concatenation)
|
||
openai_tools = adapter.tools + adapter.resources + adapter.prompts
|
||
|
||
# Use tools with OpenAI's SDK (not agent in this case)
|
||
openai = OpenAI()
|
||
messages = [{"role": "user", "content": "Please tell me the cheapest hotel for two people in Trapani."}]
|
||
response = openai.chat.completions.create(model="gpt-5.5", messages=messages, tools=openai_tools)
|
||
|
||
response_message = response.choices[0].message
|
||
messages.append(response_message)
|
||
if not response_message.tool_calls:
|
||
print("No tool call requested by the model")
|
||
print(response_message.content)
|
||
return
|
||
|
||
# Handle the tool calls (Tools, Resources, Prompts...)
|
||
for tool_call in response_message.tool_calls:
|
||
import json
|
||
|
||
function_name = tool_call.function.name
|
||
arguments = json.loads(tool_call.function.arguments)
|
||
|
||
# Use the adapter's map to get the correct executor
|
||
executor = adapter.tool_executors.get(function_name)
|
||
|
||
if not executor:
|
||
print(f"Error: Unknown tool '{function_name}' requested by model.")
|
||
content = f"Error: Tool '{function_name}' not found."
|
||
else:
|
||
try:
|
||
# Execute the tool using the retrieved function
|
||
print(f"Executing tool: {function_name}({arguments})")
|
||
tool_result = await executor(**arguments)
|
||
|
||
# Use the adapter's universal parser
|
||
content = adapter.parse_result(tool_result)
|
||
except Exception as e:
|
||
print(f"An unexpected error occurred while executing tool {function_name}: {e}")
|
||
content = f"Error executing tool: {e}"
|
||
|
||
# Append the result for this specific tool call
|
||
messages.append({"tool_call_id": tool_call.id, "role": "tool", "name": function_name, "content": content})
|
||
|
||
# Send the tool result back to the model
|
||
second_response = openai.chat.completions.create(model="gpt-5.5", messages=messages, tools=openai_tools)
|
||
final_message = second_response.choices[0].message
|
||
print("\n--- Final response from the model ---")
|
||
print(final_message.content)
|
||
|
||
except Exception as e:
|
||
print(f"Error: {e}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
asyncio.run(main())
|
||
```
|