1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211# Replace the illustrative IDs and URLs below with your own resource values."""Sample MCP Server for ChatGPT IntegrationThis server implements the Model Context Protocol (MCP) with search and fetchcapabilities designed to work with ChatGPT's chat and deep research features."""import loggingimport osfrom typing import Anyfrom fastmcp import FastMCPfrom openai import OpenAIfrom pydantic import BaseModelclassSearchResult(BaseModel):id: str title: str url: strclassSearchOutput(BaseModel): results: list[SearchResult]classFetchOutput(BaseModel):id: str title: str text: str url: str metadata: dict[str, Any] |None=None# Configure logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# OpenAI configurationOPENAI_API_KEY= os.environ["OPENAI_API_KEY"]VECTOR_STORE_ID="vs_123"# Initialize OpenAI clientopenai_client = OpenAI(api_key=OPENAI_API_KEY)server_instructions ="""This MCP server provides search and document retrieval capabilitiesfor ChatGPT Apps and deep research. Use the search tool to find relevant documentsbased on keywords, then use the fetch tool to retrieve completedocument content with citations."""defcreate_server():"""Create and configure the MCP server with search and fetch tools."""# Initialize the FastMCP server mcp = FastMCP(name="Sample MCP Server", instructions=server_instructions)@mcp.tool(output_schema=SearchOutput.model_json_schema())asyncdefsearch(query: str) -> SearchOutput:""" Search for documents using OpenAI Vector Store search. This tool searches through the vector store to find semantically relevant matches. Returns a list of search results with basic information. Use the fetch tool to get complete document content. Args: query: Search query string. Natural language queries work best for semantic search. Returns: Dictionary with 'results' key containing list of matching documents. Each result includes id, title, and URL. """ifnot query ornot query.strip():return SearchOutput(results=[])ifnot openai_client: logger.error("OpenAI client not initialized - API key missing")raiseValueError("OpenAI API key is required for vector store search")# Search the vector store using OpenAI API logger.info(f"Searching {VECTOR_STORE_ID} for query: '{query}'") response = openai_client.vector_stores.search(vector_store_id=VECTOR_STORE_ID, query=query ) results = []# Process the vector store search resultsifhasattr(response, "data") and response.data:for i, item inenumerate(response.data):# Extract file_id, filename, and content item_id =getattr(item, "file_id", f"vs_{i}") item_filename =getattr(item, "filename", f"Document {i +1}") result = SearchResult(id=item_id,title=item_filename,url=f"https://platform.openai.com/storage/files/{item_id}", ) results.append(result) logger.info(f"Vector store search returned {len(results)} results")return SearchOutput(results=results)@mcp.tool(output_schema=FetchOutput.model_json_schema())asyncdeffetch(id: str) -> FetchOutput:""" Retrieve complete document content by ID for detailed analysis and citation. This tool fetches the full document content from OpenAI Vector Store. Use this after finding relevant documents with the search tool to get complete information for analysis and proper citation. Args: id: File ID from vector store (file-xxx) or local document ID Returns: Complete document with id, title, full text content, optional URL, and metadata Raises: ValueError: If the specified ID is not found """ifnotid:raiseValueError("Document ID is required")ifnot openai_client: logger.error("OpenAI client not initialized - API key missing")raiseValueError("OpenAI API key is required for vector store file retrieval" ) logger.info(f"Fetching content from vector store for file ID: {id}")# Fetch file content from vector store content_response = openai_client.vector_stores.files.content(vector_store_id=VECTOR_STORE_ID, file_id=id )# Get file metadata file_info = openai_client.vector_stores.files.retrieve(vector_store_id=VECTOR_STORE_ID, file_id=id )# Extract content from paginated response file_content =""ifhasattr(content_response, "data") and content_response.data:# Combine all content chunks from FileContentResponse objects content_parts = []for content_item in content_response.data:ifhasattr(content_item, "text"): content_parts.append(content_item.text) file_content ="\n".join(content_parts)else: file_content ="No content available"# Use filename as title and create proper URL for citations filename = openai_client.files.retrieve(file_id=id).filename result = FetchOutput(id=id,title=filename,text=file_content,url=f"https://platform.openai.com/storage/files/{id}", )# Add metadata if available from file infoifhasattr(file_info, "attributes") and file_info.attributes: result.metadata =dict(file_info.attributes) logger.info(f"Fetched vector store file: {id}")return resultreturn mcpdefmain():"""Main function to start the MCP server.""" logger.info(f"Using vector store: {VECTOR_STORE_ID}")# Create the MCP server server = create_server()# Configure and start the server logger.info("Starting MCP server on 0.0.0.0:8000") logger.info("Server will be accessible via SSE transport")try:# Use FastMCP's built-in run method with SSE transport port =int(os.environ.get("OPENAI_EXAMPLE_PORT", "8000")) server.run(transport="sse",host="0.0.0.0",port=port,uvicorn_config={"loop": "asyncio"}, )exceptKeyboardInterrupt: logger.info("Server stopped by user")exceptExceptionas e: logger.error(f"Server error: {e}")raiseif__name__=="__main__": main()