SPB Git

Repository Public

mcp.md 30.1 KB 526 lines markdown

1# Building MCP servers for plugins and API integrations23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45[Model Context Protocol](https://modelcontextprotocol.io/introduction) (MCP) is an open protocol that's becoming the industry standard for extending AI models with additional tools and knowledge. Remote MCP servers can be used to connect models over the Internet to new data sources and capabilities.67In this guide, we'll cover how to build a remote MCP server that reads data from a private data source (a [vector store](https://developers.openai.com/api/docs/guides/retrieval)) and makes it available through a plugin in ChatGPT and Codex, through ChatGPT deep research and company knowledge, and [through the API](https://developers.openai.com/api/docs/guides/deep-research).89**Note**: To build a plugin with an MCP server, start with the plugin docs: [Quickstart](https://developers.openai.com/plugins/quickstart), [Build your MCP server](https://developers.openai.com/plugins/build/mcp-server), [Connect and test your plugin](https://developers.openai.com/plugins/deploy/connect-chatgpt), and [Authentication](https://developers.openai.com/plugins/build/auth). If your MCP server doesn't need UI, you can expose tools without UI resources.1011## Configure a data source1213You can use data from any source to power a remote MCP server, but for simplicity, we will use [vector stores](https://developers.openai.com/api/docs/guides/retrieval) in the OpenAI API. Begin by uploading a PDF document to a new vector store - [you can use this public domain 19th century book about cats](https://cdn.openai.com/API/docs/cats.pdf) for an example.1415You can upload files and create a vector store [in the dashboard here](https://platform.openai.com/storage/vector_stores), or you can create vector stores and upload files via API. [Follow the vector store guide](https://developers.openai.com/api/docs/guides/retrieval) to set up a vector store and upload a file to it.1617Make a note of the vector store's unique ID to use in the example to follow.1819![vector store configuration](https://cdn.openai.com/API/docs/images/vector_store.png)2021## Create an MCP server2223Next, let's create a remote MCP server that will do search queries against our vector store, and be able to return document content for files with a given ID.2425In this example, we are going to build our MCP server using Python and [FastMCP](https://github.com/jlowin/fastmcp). A full implementation of the server appears at the end of this section, along with instructions for running it in a [browser-based development environment](https://replit.com/).2627Note that there are a number of other MCP server frameworks you can use in a variety of programming languages. Whichever framework you use though, the tool definitions in your server will need to conform to the shape described here.2829To work with ChatGPT deep research and company knowledge, your MCP server30should implement two read-only tools: `search` and `fetch`, using the31compatibility schema in [Company knowledge compatibility](https://developers.openai.com/plugins/build/mcp-server#company-knowledge-compatibility).32The same interface is useful for research workflows via API.3334Declare an output schema for each tool so clients can validate the result shape.35In FastMCP, typed return models can generate this schema automatically; the36example below passes `output_schema` explicitly from the same models.3738### `search` tool3940The `search` tool is responsible for returning a list of relevant search results from your MCP server's data source, given a user's query.4142_Arguments:_4344A single query string.4546_Returns:_4748An object with a single key, `results`, whose value is an array of result objects. Each result object should include:4950- `id` - a unique ID for the document or search result item51- `title` - human-readable title.52- `url` - canonical URL for citation.5354In MCP, return this object as `structuredContent` and include the same value as55a JSON-encoded string in the [content array](https://modelcontextprotocol.io/docs/learn/architecture#understanding-the-tool-execution-response)56for compatibility.5758The final tool response should look like:5960```json61{62  "structuredContent": {63    "results": [{ "id": "doc-1", "title": "...", "url": "..." }]64  },65  "content": [66    {67      "type": "text",68      "text": "{\"results\":[{\"id\":\"doc-1\",\"title\":\"...\",\"url\":\"...\"}]}"69    }70  ]71}72```7374### `fetch` tool7576The fetch tool is used to retrieve the full contents of a search result document or item.7778_Arguments:_7980A string which is a unique identifier for the search document.8182_Returns:_8384A single object with the following properties:8586- `id` - a unique ID for the document or search result item87- `title` - a string title for the search result item88- `text` - The full text of the document or item89- `url` - a URL to the document or search result item. Useful for citing90  specific resources in research.91- `metadata` - an optional key/value pairing of data about the result9293In MCP, return this object as `structuredContent` and include the same value as94a JSON-encoded string in the content array for compatibility.9596The final tool response should look like:9798```json99{100  "structuredContent": {101    "id": "doc-1",102    "title": "...",103    "text": "full text...",104    "url": "https://example.com/doc",105    "metadata": { "source": "vector_store" }106  },107  "content": [108    {109      "type": "text",110      "text": "{\"id\":\"doc-1\",\"title\":\"...\",\"text\":\"full text...\",\"url\":\"https://example.com/doc\",\"metadata\":{\"source\":\"vector_store\"}}"111    }112  ]113}114```115116### Citation behavior117118For both `search` results and `fetch` responses, ChatGPT creates citation119metadata only when `url` is a non-empty string. A result with a `title` but no120usable `url` remains ordinary tool output instead of becoming an empty121citation. To make a result citable, return its canonical `url`.122123For example, ChatGPT might call `search` with:124125```json126{ "query": "What is the quarterly plan?" }127```128129The MCP server can respond with a URL-backed result:130131```json132{133  "structuredContent": {134    "results": [135      {136        "id": "quarterly-plan",137        "title": "Quarterly plan",138        "url": "https://example.com/quarterly-plan"139      }140    ]141  },142  "content": [143    {144      "type": "text",145      "text": "{\"results\":[{\"id\":\"quarterly-plan\",\"title\":\"Quarterly plan\",\"url\":\"https://example.com/quarterly-plan\"}]}"146    }147  ]148}149```150151In this response, the `url` field has a value, which makes the result eligible152for citation metadata. The query itself does not trigger citation handling. If153the result omits `url`, or provides an empty or non-string value, ChatGPT154preserves the result as ordinary tool output.155156### Server example157158You can try this example MCP server in a [browser-based development environment](https://replit.com/). Configure the sample with your own API credentials and vector store information.159160[Example MCP server on Replit161162163164      Remix the server example on Replit to test live.](https://replit.com/@kwhinnery-oai/DeepResearchServer?v=1#README.md)165166A full implementation of both the `search` and `fetch` tools in FastMCP is below also for convenience.167168169170#### Full implementation - FastMCP server171172173174```python175# Replace the illustrative IDs and URLs below with your own resource values.176"""177Sample MCP Server for ChatGPT Integration178179This server implements the Model Context Protocol (MCP) with search and fetch180capabilities designed to work with ChatGPT's chat and deep research features.181"""182183import logging184import os185from typing import Any186187from fastmcp import FastMCP188from openai import OpenAI189from pydantic import BaseModel190191192class SearchResult(BaseModel):193    id: str194    title: str195    url: str196197198class SearchOutput(BaseModel):199    results: list[SearchResult]200201202class FetchOutput(BaseModel):203    id: str204    title: str205    text: str206    url: str207    metadata: dict[str, Any] | None = None208209210# Configure logging211logging.basicConfig(level=logging.INFO)212logger = logging.getLogger(__name__)213214# OpenAI configuration215OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]216VECTOR_STORE_ID = "vs_123"217218# Initialize OpenAI client219openai_client = OpenAI(api_key=OPENAI_API_KEY)220221server_instructions = """222This MCP server provides search and document retrieval capabilities223for ChatGPT Apps and deep research. Use the search tool to find relevant documents224based on keywords, then use the fetch tool to retrieve complete225document content with citations.226"""227228229def create_server():230    """Create and configure the MCP server with search and fetch tools."""231232    # Initialize the FastMCP server233    mcp = FastMCP(name="Sample MCP Server", instructions=server_instructions)234235    @mcp.tool(output_schema=SearchOutput.model_json_schema())236    async def search(query: str) -> SearchOutput:237        """238        Search for documents using OpenAI Vector Store search.239240        This tool searches through the vector store to find semantically relevant matches.241        Returns a list of search results with basic information. Use the fetch tool to get242        complete document content.243244        Args:245            query: Search query string. Natural language queries work best for semantic search.246247        Returns:248            Dictionary with 'results' key containing list of matching documents.249            Each result includes id, title, and URL.250        """251        if not query or not query.strip():252            return SearchOutput(results=[])253254        if not openai_client:255            logger.error("OpenAI client not initialized - API key missing")256            raise ValueError("OpenAI API key is required for vector store search")257258        # Search the vector store using OpenAI API259        logger.info(f"Searching {VECTOR_STORE_ID} for query: '{query}'")260261        response = openai_client.vector_stores.search(262            vector_store_id=VECTOR_STORE_ID, query=query263        )264265        results = []266267        # Process the vector store search results268        if hasattr(response, "data") and response.data:269            for i, item in enumerate(response.data):270                # Extract file_id, filename, and content271                item_id = getattr(item, "file_id", f"vs_{i}")272                item_filename = getattr(item, "filename", f"Document {i + 1}")273274                result = SearchResult(275                    id=item_id,276                    title=item_filename,277                    url=f"https://platform.openai.com/storage/files/{item_id}",278                )279280                results.append(result)281282        logger.info(f"Vector store search returned {len(results)} results")283        return SearchOutput(results=results)284285    @mcp.tool(output_schema=FetchOutput.model_json_schema())286    async def fetch(id: str) -> FetchOutput:287        """288        Retrieve complete document content by ID for detailed289        analysis and citation. This tool fetches the full document290        content from OpenAI Vector Store. Use this after finding291        relevant documents with the search tool to get complete292        information for analysis and proper citation.293294        Args:295            id: File ID from vector store (file-xxx) or local document ID296297        Returns:298            Complete document with id, title, full text content,299            optional URL, and metadata300301        Raises:302            ValueError: If the specified ID is not found303        """304        if not id:305            raise ValueError("Document ID is required")306307        if not openai_client:308            logger.error("OpenAI client not initialized - API key missing")309            raise ValueError(310                "OpenAI API key is required for vector store file retrieval"311            )312313        logger.info(f"Fetching content from vector store for file ID: {id}")314315        # Fetch file content from vector store316        content_response = openai_client.vector_stores.files.content(317            vector_store_id=VECTOR_STORE_ID, file_id=id318        )319320        # Get file metadata321        file_info = openai_client.vector_stores.files.retrieve(322            vector_store_id=VECTOR_STORE_ID, file_id=id323        )324325        # Extract content from paginated response326        file_content = ""327        if hasattr(content_response, "data") and content_response.data:328            # Combine all content chunks from FileContentResponse objects329            content_parts = []330            for content_item in content_response.data:331                if hasattr(content_item, "text"):332                    content_parts.append(content_item.text)333            file_content = "\n".join(content_parts)334        else:335            file_content = "No content available"336337        # Use filename as title and create proper URL for citations338        filename = getattr(file_info, "filename", f"Document {id}")339340        result = FetchOutput(341            id=id,342            title=filename,343            text=file_content,344            url=f"https://platform.openai.com/storage/files/{id}",345        )346347        # Add metadata if available from file info348        if hasattr(file_info, "attributes") and file_info.attributes:349            result.metadata = dict(file_info.attributes)350351        logger.info(f"Fetched vector store file: {id}")352        return result353354    return mcp355356357def main():358    """Main function to start the MCP server."""359    logger.info(f"Using vector store: {VECTOR_STORE_ID}")360361    # Create the MCP server362    server = create_server()363364    # Configure and start the server365    logger.info("Starting MCP server on 0.0.0.0:8000")366    logger.info("Server will be accessible via SSE transport")367368    try:369        # Use FastMCP's built-in run method with SSE transport370        port = int(os.environ.get("OPENAI_EXAMPLE_PORT", "8000"))371        server.run(372            transport="sse",373            host="0.0.0.0",374            port=port,375            uvicorn_config={"loop": "asyncio"},376        )377    except KeyboardInterrupt:378        logger.info("Server stopped by user")379    except Exception as e:380        logger.error(f"Server error: {e}")381        raise382383384if __name__ == "__main__":385    main()386```387388389390391392393394395#### Replit setup396397398399On Replit, configure `OPENAI_API_KEY` with your OpenAI API key in the "Secrets" UI. In the sample, replace `vs_123` with the ID of the vector store you created earlier for search.400401On free Replit accounts, server URLs are active for as long as the editor is active, so while you are testing, you'll need to keep the browser tab open. You can get a URL for your MCP server by clicking on the chainlink icon:402403![replit configuration](https://cdn.openai.com/API/docs/images/replit.png)404405In the long dev URL, ensure it ends with `/sse/`, which is the server-sent events (streaming) interface to the MCP server. This is the URL you will use to connect your app in ChatGPT and call it via API. An example Replit URL looks like:406407```408https://777xxx.janeway.replit.dev/sse/409```410411412413414415## Test and connect your MCP server416417You can test your MCP server with a deep research model [in the prompts dashboard](https://platform.openai.com/chat). Create a new prompt, or edit an existing one, and add a new MCP tool to the prompt configuration. This compatibility example exposes only read-only `search` and `fetch` tools, so its API request skips approval for those tools. Keep approval enabled for tools that can modify data or take other consequential actions.418419If you are testing this server as part of a plugin, follow [Connect and test your plugin](https://developers.openai.com/plugins/deploy/connect-chatgpt).420421![prompts configuration](https://cdn.openai.com/API/docs/images/prompts_mcp.png)422423Once you have configured your MCP server, you can chat with a model using it via the Prompts UI.424425![prompts chat](https://cdn.openai.com/API/docs/images/chat_prompts_mcp.png)426427You can test the MCP server using the Responses API directly with a request like this one:428429```bash430curl https://api.openai.com/v1/responses \431  -H "Content-Type: application/json" \432  -H "Authorization: Bearer $OPENAI_API_KEY" \433  -d '{434  "model": "gpt-5.6-sol",435  "input": [436    {437      "role": "developer",438      "content": [439        {440          "type": "input_text",441          "text": "You are a research assistant that searches MCP servers to find answers to your questions."442        }443      ]444    },445    {446      "role": "user",447      "content": [448        {449          "type": "input_text",450          "text": "Are cats attached to their homes? Give a succinct one page overview."451        }452      ]453    }454  ],455  "reasoning": {456    "summary": "auto"457  },458  "tools": [459    {460      "type": "mcp",461      "server_label": "cats",462      "server_url": "https://777ff573-9947-4b9c-8982-658fa40c7d09-00-3le96u7wsymx.janeway.replit.dev/sse/",463      "allowed_tools": [464        "search",465        "fetch"466      ],467      "require_approval": "never"468    }469  ]470}'471```472473474### Handle authentication475476As someone building a custom remote MCP server, authorization and authentication help you protect your data. We recommend using OAuth with [Client ID Metadata Documents](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#client-id-metadata-documents) for client registration when your authorization server supports CIMD and the plugin creator chooses it. ChatGPT supports CIMD with public-client token exchange (`none`) or signed client assertion token exchange (`private_key_jwt`). Dynamic client registration remains supported when configured. For plugin authentication requirements, see [Authentication](https://developers.openai.com/plugins/build/auth). For protocol details, read the [MCP user guide](https://modelcontextprotocol.io/docs/concepts/transports#authentication-and-authorization) or the [authorization specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization).477478If you connect your custom remote MCP server through a plugin, users in your workspace will get an OAuth flow to your service.479480### Connect in ChatGPT4814821. In [ChatGPT](https://chatgpt.com), open **Settings → Security and login** and turn on **Developer mode**.4831. Go to [ChatGPT Plugins](https://chatgpt.com/plugins), select the plus button, and connect your server URL in developer mode.4841. Test your plugin by running prompts in chat and deep research.485486For detailed setup steps, see [Connect and test your plugin](https://developers.openai.com/plugins/deploy/connect-chatgpt).487488## Risks and safety489490Custom MCP servers enable you to connect your ChatGPT workspace to external applications, which allows ChatGPT to access, send and receive data in these applications. Please note that custom MCP servers are not developed or verified by OpenAI, and are third-party services that are subject to their own terms and conditions.491492If you come across a malicious MCP server, please report it to security@openai.com.493494### Prompt injection-related risks495496Prompt injections are a form of attack where an attacker embeds malicious instructions in content that one of our models is likely to encounter–such as a webpage–with the intention that the instructions override ChatGPT’s intended behavior. If the model obeys the injected instructions it may take actions the user and developer never intended—including sending private data to an external destination.497498For example, you might ask ChatGPT to find a restaurant for a group dinner by checking your calendar and recent emails. While researching, it might encounter a malicious comment—essentially a harmful piece of content designed to trick the agent into performing unintended actions—directing it to retrieve a password reset code from Gmail and send it to a malicious website.499500Below is a table of specific scenarios to consider. We recommend reviewing this table carefully to inform your decision about whether to use custom MCPs.501502| Scenario / Risk                                                                                                                                                                                                                                                                                                                                                                                                                       | Is it safe if I trust the MCP’s developer?                                                                                                                                                                                                                                                       | What can I do to reduce risk?                                                                                                                                                                                                                                                                                                  |503| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |504| An attacker may somehow insert a prompt injection attack into data accessible via the MCP. <br /><br />_Examples:_<br />• For a customer support MCP, an attacker could send you a customer support request with a prompt injection attack.                                                                                                                                                                                           | Trusting a MCP’s developer does not make this safe.<br /><br />For this to be safe you need to trust _all content that can be accessed within the MCP_.                                                                                                                                          | • Do not use a MCP if it could contain malicious or untrusted user input, even if you trust the developer of the MCP.<br />• Configure access to minimize how many people have access to the MCP.                                                                                                                              |505| A malicious MCP may request excessive parameters to a read or write action. <br /><br />_Example:_<br />• An employee flight booking MCP could expose a read action to get a flight schedule, but request parameters including `summaryOfConversation`, `userAnnualIncome`, `userHomeAddress`.                                                                                                                                        | Trusting a MCP’s developer does not necessarily make this safe.<br /><br />A MCP’s developer may consider it reasonable to be requesting certain data that you do not consider acceptable to share.                                                                                              | • When installing MCP servers manually, review the parameters requested for each action and ensure there is no privacy overreach.                                                                                                                                                                                              |506| An attacker may use a prompt injection attack to trick ChatGPT into fetching sensitive data from a custom MCP, to then be sent to the attacker. <br /><br />_Example:_<br />• An attacker may deliver a prompt injection attack to one of the enterprise users via a different MCP (for example, email), where the attack attempts to trick ChatGPT into reading sensitive data from an internal tool and sending it to the attacker. | Trusting a MCP’s developer does not make this safe.<br /><br />Everything within the new MCP could be safe and trusted since the risk is this data being stolen by attacks coming from a different malicious source.                                                                             | • _ChatGPT is designed to protect users_, but attackers may attempt to steal your data, so be aware of the risk and consider whether taking it makes sense.<br />• Configure access to minimize how many people have access to MCPs with particularly sensitive data.                                                          |507| An attacker may use a prompt injection attack to leak sensitive information through a write action to a custom MCP. <br /><br />_Example:_<br />• An attacker uses a prompt injection attack through a different MCP to trick ChatGPT into fetching sensitive data, then using an MCP for a customer support system to send it to the attacker.                                                                                       | Trusting a MCP’s developer does not make this safe.<br /><br />Even if you fully trust the MCP, if write actions have any consequences that can be observed by an attacker, they could attempt to take advantage of it.                                                                          | • Users should review write actions carefully when they happen (to ensure they were intended and do not contain any data that shouldn’t be shared).                                                                                                                                                                            |508| An attacker may use a prompt injection attack to leak sensitive information through a read action to a malicious custom MCP because the MCP can log these actions.                                                                                                                                                                                                                                                                    | This attack only works if the MCP is malicious, or if the MCP incorrectly marks write actions as read actions.<br /><br />If you trust a MCP’s developer to correctly only mark read actions as _read_, and trust that developer to not attempt to steal data, then this risk is likely minimal. | • Only use MCPs from developers that you trust (though note this isn’t sufficient to make it safe).                                                                                                                                                                                                                            |509| An attacker may use a prompt injection attack to trick ChatGPT into taking a harmful or destructive write action via a custom MCP that users did not intend.                                                                                                                                                                                                                                                                          | Trusting a MCP’s developer does not make this safe.<br /><br />Everything within the new MCP could be safe and trusted, and this risk still exists since the attack comes from a different malicious source.                                                                                     | • Users should carefully review write actions to ensure they are intended and correct.<br />• ChatGPT is designed to protect users, but attackers may attempt to trick ChatGPT into taking unintended write actions.<br />• Configure access to minimize how many people have access to MCPs with particularly sensitive data. |510511### Non-prompt injection related risks512513Custom MCPs introduce other risks unrelated to prompt injection attacks:514515- **Write actions can increase both the usefulness and the risks of MCP servers**, because they make it possible for the server to take potentially destructive actions rather than only providing information back to ChatGPT. ChatGPT currently requires manual confirmation in any conversation before write actions can be taken. The confirmation will flag potentially sensitive data but you should only use write actions in situations where you have carefully considered, and are comfortable with, the possibility that ChatGPT might make a mistake involving such an action. It is possible for write actions to occur even if the MCP server has tagged the action as read only, making it even more important that you trust the custom MCP server before deploying to ChatGPT.516- **Any MCP server may receive sensitive data as part of querying**. Even when the server is not malicious, it will have access to whatever data ChatGPT supplies during the interaction, potentially including sensitive data the user may earlier have provided to ChatGPT. For instance, such data could be included in queries ChatGPT sends to the MCP server when using deep research or chat app tools.517518### Connecting to trusted servers519520We recommend that you do not connect to a custom MCP server unless you know and trust the underlying application.521522For example, choose official servers hosted by the service providers themselves. Connect to the Stripe server hosted by Stripe at `mcp.stripe.com` instead of an unofficial Stripe MCP server hosted by a third party. Because few official MCP servers are available today, you may consider a server hosted by an organization that proxies requests to another service through an API. Only connect after you have reviewed how the organization uses your data and verified that you can trust the server. When building and connecting to your own MCP server, double-check that it's the correct server. Be careful about the data you provide in response to requests and how you treat data sent to you when OpenAI calls your MCP server.523524Your remote MCP server permits others to connect OpenAI to your services and allows OpenAI to access, send and receive data, and take action in these services. Avoid putting any sensitive information in the JSON for your tools, and avoid storing any sensitive information from ChatGPT users accessing your remote MCP server.525526As someone building an MCP server, don't put anything malicious in your tool definitions.
Files main
Menu

Theme