模型上下文协议 (MCP)是一种开放协议,用于为 AI 模型接入更多工具和知识,正逐渐成为行业标准。通过远程 MCP 服务器,模型可以经由互联网访问新的数据源并使用新的功能。
本指南介绍如何构建远程 MCP 服务器,从私有数据源(一个向量存储 )读取数据。您可以通过 ChatGPT 和 Codex 中的插件、ChatGPT 的深度研究和公司知识功能,以及 API 访问这些数据。
注意 :要使用 MCP 服务器构建插件,请先阅读插件文档中的快速入门 、构建 MCP 服务器 、连接并测试插件 和身份验证 。如果您的 MCP 服务器不需要用户界面,就可以直接提供工具,无需提供界面资源。
远程 MCP 服务器可以使用任何来源的数据。为简化示例,这里使用 OpenAI API 的向量存储 。首先,将一份 PDF 文档上传到新的向量存储。您可以用这本介绍猫的 19 世纪公版书作为示例 。
您可以在控制台中 上传文件并创建向量存储,也可以通过 API 创建向量存储并上传文件。请按照向量存储指南 设置向量存储,并向其中上传一个文件。
记下向量存储的唯一 ID,后面的示例会用到它。
接下来,创建一个远程 MCP 服务器,让它能够搜索向量存储,并根据给定的文件 ID 返回文档内容。
本示例使用 Python 和 FastMCP 构建 MCP 服务器。本节末尾提供了服务器的完整实现,并说明了如何在浏览器开发环境 中运行它。
多种编程语言都有其他可用的 MCP 服务器框架。无论使用哪种框架,服务器上的工具定义都必须符合下文描述的结构。
要支持 ChatGPT 的深度研究和公司知识功能,您的 MCP 服务器应实现两个只读工具 search 和 fetch,并遵循公司知识兼容性 一节中的兼容性模式。通过 API 开展研究时,也可以使用同一套接口。
请为每个工具声明输出模式,以便客户端验证结果的结构。在 FastMCP 中,带有类型定义的返回模型可以自动生成该模式。下方示例使用相同的模型生成 output_schema 并显式传入。
search 工具根据用户的查询在 MCP 服务器的数据源中搜索,并返回相关结果列表。
参数
一个查询字符串。
返回值
一个仅含 results 键的对象,该键的值是由搜索结果对象组成的数组。每个结果对象应包含以下字段。
id 表示文档或搜索结果项的唯一 ID。
title 是便于阅读的标题。
url 是用于引用的规范 URL。
在 MCP 中,以 structuredContent 的形式返回该对象。为确保兼容性,还要将同一个值编码为 JSON 字符串,放入内容数组 。
工具的最终响应应如下所示。
1 2 3 4 5 6 7 8 9 10 11 {
"structuredContent" : {
"results" : [{ "id" : "doc-1" , "title" : "..." , "url" : "..." }]
},
"content" : [
{
"type" : "text" ,
"text" : "{ \" results \" :[{ \" id \" : \" doc-1 \" , \" title \" : \" ... \" , \" url \" : \" ... \" }]}"
}
]
}
fetch 工具用于获取搜索结果中文档或条目的完整内容。
参数
一个字符串,表示搜索结果中文档的唯一标识符。
返回值
一个包含以下属性的对象。
id 表示文档或搜索结果项的唯一 ID。
title 是搜索结果项的标题,类型为字符串。
text 是文档或条目的全文。
url 指向文档或搜索结果项,方便在研究中引用具体资源。
metadata 是可选字段,以键值对形式提供与结果相关的数据。
在 MCP 中,以 structuredContent 的形式返回该对象。为确保兼容性,还要将同一个值编码为 JSON 字符串,放入内容数组。
工具的最终响应应如下所示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 {
"structuredContent" : {
"id" : "doc-1" ,
"title" : "..." ,
"text" : "full text..." ,
"url" : "https://example.com/doc" ,
"metadata" : { "source" : "vector_store" }
},
"content" : [
{
"type" : "text" ,
"text" : "{ \" id \" : \" doc-1 \" , \" title \" : \" ... \" , \" text \" : \" full text... \" , \" url \" : \" https://example.com/doc \" , \" metadata \" :{ \" source \" : \" vector_store \" }}"
}
]
}
对于 search 结果和 fetch 响应,只有当 url 是非空字符串时,ChatGPT 才会创建引用元数据。如果结果有 title 但缺少可用的 url,ChatGPT 会将其保留为普通工具输出,不会生成空引用。要让结果可供引用,请返回其规范 url。
例如,ChatGPT 可能会使用以下参数调用 search。
{ "query" : "What is the quarterly plan?" }
MCP 服务器可以返回如下带有 URL 的结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 {
"structuredContent" : {
"results" : [
{
"id" : "quarterly-plan" ,
"title" : "Quarterly plan" ,
"url" : "https://example.com/quarterly-plan"
}
]
},
"content" : [
{
"type" : "text" ,
"text" : "{ \" results \" :[{ \" id \" : \" quarterly-plan \" , \" title \" : \" Quarterly plan \" , \" url \" : \" https://example.com/quarterly-plan \" }]}"
}
]
}
在此响应中,url 字段有值,因此 ChatGPT 可以为该结果创建引用元数据。查询本身不会触发引用处理。如果结果省略了 url,或者提供的值为空或不是字符串,ChatGPT 会将结果保留为普通工具输出。
您可以在浏览器开发环境 中试用这个 MCP 服务器示例。请使用您自己的 API 凭据和向量存储信息配置示例。
在 Replit 上创建服务器示例的副本并在线测试。
以下示例均实现了 search 和 fetch 两个工具。Python 示例使用 FastMCP。Java 示例使用 com.openai:openai-java:4.105.0、io.modelcontextprotocol.sdk:mcp-core:1.1.5、io.modelcontextprotocol.sdk:mcp-json-jackson2:1.1.5 和 org.eclipse.jetty.ee10:jetty-ee10-servlet:12.0.41。请将 Java 初始化代码放在服务器类的 main 方法中,设置 OPENAI_API_KEY,并将 vs_123 替换为您的向量存储 ID。Java 服务器在 /sse 路径上提供 SSE 端点。
支持搜索和获取文档的服务器实现 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 import OpenAI from "openai" ;
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" ;
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js" ;
import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js" ;
import { z } from "zod" ;
const client = new OpenAI ();
// Replace this illustrative ID with your existing document store ID.
const vectorStoreID = "vs_123" ;
const citation = ( id : string ) =>
`https://platform.openai.com/storage/files/${ encodeURIComponent ( id ) }` ;
function createServer () {
const server = new McpServer (
{ name: "Sample MCP Server" , version: "1.0.0" },
{
instructions:
"Search for relevant documents, then fetch complete content with citations." ,
}
);
server. registerTool (
"search" ,
{
description:
"Search documents and return identities, titles, and citation URLs." ,
inputSchema: { query: z. string () },
outputSchema: {
results: z. array (
z. object ({ id: z. string (), title: z. string (), url: z. string () })
),
},
},
async ({ query }) => {
const results : { id : string ; title : string ; url : string }[] = [];
if (query. trim ()) {
const page = await client.vectorStores. search (vectorStoreID, { query });
for ( const item of page.data)
results. push ({
id: item.file_id,
title: item.filename,
url: citation (item.file_id),
});
}
const result = { results };
return {
content: [{ type: "text" , text: JSON . stringify (result) }],
structuredContent: result,
};
}
);
server. registerTool (
"fetch" ,
{
description:
"Retrieve a complete document with its citation and metadata." ,
inputSchema: { id: z. string (). min ( 1 ) },
outputSchema: {
id: z. string (),
title: z. string (),
text: z. string (),
url: z. string (),
metadata: z. record (z. string (), z. unknown ()),
},
},
async ({ id }) => {
const parts : string [] = [];
for await ( const item of client.vectorStores.files. content (id, {
vector_store_id: vectorStoreID,
})) {
if ( typeof item.text !== "string" )
throw new Error ( "Document content omitted text" );
parts. push (item.text);
}
const attachment = await client.vectorStores.files. retrieve (id, {
vector_store_id: vectorStoreID,
});
const file = await client.files. retrieve (id);
const result = {
id,
title: file.filename,
text: parts. join ( " \n " ),
url: citation (id),
metadata: attachment.attributes ?? {},
};
return {
content: [{ type: "text" , text: JSON . stringify (result) }],
structuredContent: result,
};
}
);
return server;
}
// Loopback binding and SDK Host validation protect this local example.
const app = createMcpExpressApp ({ host: "127.0.0.1" });
app. all ( "/mcp" , async ( request , response ) => {
const server = createServer ();
const transport = new StreamableHTTPServerTransport ({
sessionIdGenerator: undefined ,
enableJsonResponse: true ,
});
response. on ( "close" , () => {
void transport. close ();
void server. close ();
});
try {
await server. connect (transport);
await transport. handleRequest (request, response, request.body);
} catch (error) {
console. error ( "MCP request failed" , error);
if ( ! response.headersSent)
response. status ( 500 ). end ( "Internal server error" );
}
});
const httpServer = app. listen ( 8000 , "127.0.0.1" ); 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 Integration
This server implements the Model Context Protocol (MCP) with search and fetch
capabilities designed to work with ChatGPT's chat and deep research features.
"""
import logging
import os
from typing import Any
from fastmcp import FastMCP
from openai import OpenAI
from pydantic import BaseModel
class SearchResult(BaseModel):
id: str
title: str
url: str
class SearchOutput(BaseModel):
results: list[SearchResult]
class FetchOutput(BaseModel):
id: str
title: str
text: str
url: str
metadata: dict[str, Any] | None = None
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# OpenAI configuration
OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
VECTOR_STORE_ID = "vs_123"
# Initialize OpenAI client
openai_client = OpenAI(api_key=OPENAI_API_KEY)
server_instructions = """
This MCP server provides search and document retrieval capabilities
for ChatGPT Apps and deep research. Use the search tool to find relevant documents
based on keywords, then use the fetch tool to retrieve complete
document content with citations.
"""
def create_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())
async def search(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.
"""
if not query or not query.strip():
return SearchOutput(results=[])
if not openai_client:
logger.error("OpenAI client not initialized - API key missing")
raise ValueError("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 results
if hasattr(response, "data") and response.data:
for i, item in enumerate(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())
async def fetch(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
"""
if not id:
raise ValueError("Document ID is required")
if not openai_client:
logger.error("OpenAI client not initialized - API key missing")
raise ValueError(
"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 = ""
if hasattr(content_response, "data") and content_response.data:
# Combine all content chunks from FileContentResponse objects
content_parts = []
for content_item in content_response.data:
if hasattr(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 info
if hasattr(file_info, "attributes") and file_info.attributes:
result.metadata = dict(file_info.attributes)
logger.info(f"Fetched vector store file: {id}")
return result
return mcp
def main():
"""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"},
)
except KeyboardInterrupt:
logger.info("Server stopped by user")
except Exception as e:
logger.error(f"Server error: {e}")
raise
if __name__ == "__main__":
main() 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 package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/openai/openai-go/v3"
"log"
"net"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
type searchInput struct {
Query string `json:"query"`
}
type searchResult struct {
ID string `json:"id"`
Title string `json:"title"`
URL string `json:"url"`
}
type searchOutput struct {
Results []searchResult `json:"results"`
}
type fetchInput struct {
ID string `json:"id"`
}
type fetchOutput struct {
ID string `json:"id"`
Title string `json:"title"`
Text string `json:"text"`
URL string `json:"url"`
Metadata map[string]any `json:"metadata,omitempty"`
}
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
client := openai.NewClient()
// Replace this illustrative ID with your existing document store ID.
store := "vs_123"
server := mcp.NewServer(&mcp.Implementation{Name: "Sample MCP Server", Version: "1.0.0"}, &mcp.ServerOptions{Instructions: "Search for relevant documents, then fetch complete content with citations."})
mcp.AddTool(server, &mcp.Tool{Name: "search", Description: "Search documents and return identities, titles, and citation URLs."}, func(ctx context.Context, _ *mcp.CallToolRequest, input searchInput) (*mcp.CallToolResult, searchOutput, error) {
result := searchOutput{Results: []searchResult{}}
if strings.TrimSpace(input.Query) == "" {
return nil, result, nil
}
page, err := client.VectorStores.Search(ctx, store, openai.VectorStoreSearchParams{Query: openai.VectorStoreSearchParamsQueryUnion{OfString: openai.String(input.Query)}})
if err != nil {
return nil, result, err
}
for _, item := range page.Data {
result.Results = append(result.Results, searchResult{ID: item.FileID, Title: item.Filename, URL: "https://platform.openai.com/storage/files/" + item.FileID})
}
return nil, result, nil
})
mcp.AddTool(server, &mcp.Tool{Name: "fetch", Description: "Retrieve a complete document with its citation and metadata."}, func(ctx context.Context, _ *mcp.CallToolRequest, input fetchInput) (*mcp.CallToolResult, fetchOutput, error) {
if input.ID == "" {
return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: "Document ID is required"}}}, fetchOutput{}, nil
}
content := client.VectorStores.Files.ContentAutoPaging(ctx, store, input.ID)
var parts []string
for content.Next() {
parts = append(parts, content.Current().Text)
}
if err := content.Err(); err != nil {
return nil, fetchOutput{}, err
}
info, err := client.VectorStores.Files.Get(ctx, store, input.ID)
if err != nil {
return nil, fetchOutput{}, err
}
file, err := client.Files.Get(ctx, input.ID)
if err != nil {
return nil, fetchOutput{}, err
}
metadata := map[string]any{}
for name, value := range info.Attributes {
var decoded any
if err := json.Unmarshal([]byte(value.RawJSON()), &decoded); err != nil {
return nil, fetchOutput{}, err
}
metadata[name] = decoded
}
return nil, fetchOutput{ID: input.ID, Title: file.Filename, Text: strings.Join(parts, "\n"), URL: "https://platform.openai.com/storage/files/" + input.ID, Metadata: metadata}, nil
})
handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server }, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true})
mux := http.NewServeMux()
mux.Handle("/mcp", handler)
port := "8000"
host := "127.0.0.1"
listener, err := net.Listen("tcp", net.JoinHostPort(host, port))
if err != nil {
log.Fatal(err)
}
httpServer := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}
fmt.Println("Listening on http://" + listener.Addr().String())
shutdownDone := make(chan struct{})
go func() {
defer close(shutdownDone)
<-ctx.Done()
shutdownCtx, stop := context.WithTimeout(context.Background(), 5*time.Second)
defer stop()
if err := httpServer.Shutdown(shutdownCtx); err != nil {
log.Print(err)
}
}()
if err := httpServer.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
<-shutdownDone
} 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 import com.fasterxml.jackson.databind.json.JsonMapper;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.ObjectMappers;
import com.openai.models.vectorstores.VectorStoreSearchParams;
import com.openai.models.vectorstores.files.*;
import io.modelcontextprotocol.json.jackson2.JacksonMcpJsonMapper;
import io.modelcontextprotocol.server.*;
import io.modelcontextprotocol.server.transport.DefaultServerTransportSecurityValidator;
import io.modelcontextprotocol.server.transport.HttpServletSseServerTransportProvider;
import io.modelcontextprotocol.spec.McpSchema;
import java.util.*;
import org.eclipse.jetty.ee10.servlet.*;
import org.eclipse.jetty.server.*;
var client = OpenAIOkHttpClient.fromEnv();
String vectorStoreId = "vs_123";
var mapper = new JacksonMcpJsonMapper(JsonMapper.builder().build());
var transport =
HttpServletSseServerTransportProvider.builder()
.jsonMapper(mapper)
.sseEndpoint("/sse")
.messageEndpoint("/messages/")
// Allow local clients and the local MCP Inspector. Add trusted hosts and origins
// explicitly when deploying this server behind a proxy.
.securityValidator(
DefaultServerTransportSecurityValidator.builder()
.allowedHosts(List.of("localhost:*", "127.0.0.1:*"))
.allowedOrigins(List.of("http://localhost:6274", "http://127.0.0.1:6274"))
.build())
.build();
var search =
McpSchema.Tool.builder()
.name("search")
.description("Search documents, then fetch complete content with citations.")
.inputSchema(
mapper,
"""
{"type":"object","properties":{"query":{"type":"string"}},"required":["query"]}
""")
.outputSchema(
mapper,
"""
{"type":"object","properties":{"results":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"url":{"type":"string"}},"required":["id","title","url"]}}},"required":["results"]}
""")
.build();
var fetch =
McpSchema.Tool.builder()
.name("fetch")
.description("Retrieve complete document text, metadata, and citation by file ID.")
.inputSchema(
mapper,
"""
{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]}
""")
.outputSchema(
mapper,
"""
{"type":"object","properties":{"id":{"type":"string"},"title":{"type":"string"},"text":{"type":"string"},"url":{"type":"string"},"metadata":{"type":["object","null"]}},"required":["id","title","text","url"]}
""")
.build();
var server =
McpServer.sync(transport)
.serverInfo("Sample MCP Server", "1.0.0")
.capabilities(McpSchema.ServerCapabilities.builder().tools(false).build())
.toolCall(
search,
(exchange, request) -> {
try {
String query = (String) request.arguments().get("query");
var results = new ArrayList<Map<String, String>>();
if (query != null && !query.isBlank()) {
var page =
client
.vectorStores()
.search(
vectorStoreId,
VectorStoreSearchParams.builder().query(query).build());
for (var item : page.data())
results.add(
Map.of(
"id",
item.fileId(),
"title",
item.filename(),
"url",
"https://platform.openai.com/storage/files/" + item.fileId()));
}
return result(Map.of("results", results));
} catch (Exception error) {
return failure(error);
}
})
.toolCall(
fetch,
(exchange, request) -> {
try {
String id = (String) request.arguments().get("id");
if (id == null || id.isBlank())
throw new IllegalArgumentException("Document ID is required");
var content =
client
.vectorStores()
.files()
.content(
id,
FileContentParams.builder().vectorStoreId(vectorStoreId).build());
var file =
client
.vectorStores()
.files()
.retrieve(
id,
FileRetrieveParams.builder().vectorStoreId(vectorStoreId).build());
var parts = new ArrayList<String>();
for (var item : content.data()) item.text().ifPresent(parts::add);
String title = client.files().retrieve(id).filename();
var document = new LinkedHashMap<String, Object>();
document.put("id", id);
document.put("title", title);
document.put("text", String.join("\n", parts));
document.put("url", "https://platform.openai.com/storage/files/" + id);
document.put(
"metadata",
file.attributes()
.map(value -> ObjectMappers.jsonMapper().valueToTree(value))
.orElse(null));
return result(document);
} catch (Exception error) {
return failure(error);
}
})
.build();
var httpServer = new Server();
var connector = new ServerConnector(httpServer);
connector.setHost("127.0.0.1");
connector.setPort(8000);
httpServer.addConnector(connector);
var context = new ServletContextHandler();
context.setContextPath("/");
context.addServlet(new ServletHolder(transport), "/*");
httpServer.setHandler(context);
try {
httpServer.start();
httpServer.join();
} finally {
server.closeGracefully();
httpServer.stop();
client.close();
}
static McpSchema.CallToolResult result(Map<String, ?> value) throws Exception {
String encoded = ObjectMappers.jsonMapper().writeValueAsString(value);
return McpSchema.CallToolResult.builder()
.structuredContent(value)
.addTextContent(encoded)
.isError(false)
.build();
}
static McpSchema.CallToolResult failure(Exception error) {
return McpSchema.CallToolResult.builder()
.isError(true)
.addTextContent(
error.getMessage() == null ? error.getClass().getSimpleName() : error.getMessage())
.build();
} 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 require "openai"
require "mcp"
require "json"
class SearchDocuments < MCP::Tool
tool_name "search"
description "Search documents and return identities, titles, and citation URLs."
input_schema(type: "object", properties: { query: { type: "string" } }, required: ["query"])
output_schema(
type: "object", properties: {
results: {
type: "array",
items: {
type: "object",
properties: {
id: { type: "string" },
title: { type: "string" },
url: { type: "string" }
},
required: %w[id title url]
}
}
}, required: ["results"]
)
def self.call(query:, server_context:)
results = []
unless query.strip.empty?
response = server_context.fetch(:client).vector_stores.search(server_context.fetch(:store), query: query)
results = response.data.map do |item|
{
id: item.file_id,
title: item.filename,
url: "https://platform.openai.com/storage/files/#{item.file_id}"
}
end
end
result = { results: results }
MCP::Tool::Response.new(
[
{
type: "text",
text: JSON.generate(result)
}
], structured_content: result
)
end
end
class FetchDocument < MCP::Tool
tool_name "fetch"
description "Retrieve a complete document with its citation and metadata."
input_schema(type: "object", properties: { id: { type: "string" } }, required: ["id"])
output_schema(
type: "object", properties: {
id: { type: "string" },
title: { type: "string" },
text: { type: "string" },
url: { type: "string" },
metadata: { type: ["object", "null"] }
}, required: %w[id title text url]
)
def self.call(id:, server_context:)
if id.empty?
return MCP::Tool::Response.new(
[
{
type: "text",
text: "Document ID is required"
}
], error: true
)
end
client = server_context.fetch(:client)
store = server_context.fetch(:store)
content = client.vector_stores.files.content(id, vector_store_id: store)
info = client.vector_stores.files.retrieve(id, vector_store_id: store)
file = client.files.retrieve(id)
text = content.data.map(&:text).join("\n")
result = {
id: id,
title: file.filename,
text: text,
url: "https://platform.openai.com/storage/files/#{id}"
}
result[:metadata] = info.attributes unless info.attributes.nil? || info.attributes.empty?
MCP::Tool::Response.new(
[
{
type: "text",
text: JSON.generate(result)
}
], structured_content: result
)
end
end
server = MCP::Server.new(
name: "Sample MCP Server", version: "1.0.0", tools: [SearchDocuments, FetchDocument],
instructions: "Search for relevant documents, then fetch complete content with citations.",
server_context: {
client: OpenAI::Client.new,
store: ENV.fetch("OPENAI_VECTOR_STORE_ID", "vs_123")
}
)
if ARGV.first == "stdio"
MCP::Server::Transports::StdioTransport.new(server).open
exit
end
require "rackup"
require "rackup/handler/webrick"
transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, stateless: true, enable_json_response: true)
app = Rack::URLMap.new("/mcp" => transport)
Rackup::Handler::WEBrick.run(app, Host: ENV.fetch("MCP_HOST", "127.0.0.1"), Port: Integer(ENV.fetch("PORT", "8000"))) do |http_server|
trap("INT") { http_server.shutdown }
trap("TERM") { http_server.shutdown }
end
配置 Replit 在 Replit 的 Secrets 界面中,将 OPENAI_API_KEY 设置为您的 OpenAI API 密钥。在示例中,将 vs_123 替换为您之前为搜索创建的向量存储的 ID。
对于 Replit 免费账户,只有编辑器处于活动状态时,服务器 URL 才可用,因此测试时请保持浏览器标签页打开。选择链接图标即可获取 MCP 服务器的 URL。
如果使用 Python 服务器,请确认较长的开发环境 URL 以 /sse/ 结尾。该路径指向 MCP 服务器的服务器发送事件(流式传输)接口。您将使用此 URL 在 ChatGPT 中连接应用,并通过 API 调用该应用。以下是 Replit URL 的示例。
https://777xxx.janeway.replit.dev/sse/ 如果使用 Ruby,请安装 openai、mcp、rackup 和 webrick gem,将 Ruby 源代码保存为 server.rb,然后运行 ruby server.rb。在 Replit 上,将 OPENAI_VECTOR_STORE_ID 设置为您的向量存储 ID,并将 MCP_HOST 设置为 0.0.0.0。Ruby 服务器在 /mcp 路径上使用 Streamable HTTP。请在连接 URL 中用该路径替换 /sse/。Ruby 服务器默认使用端口 8000,也可通过 PORT 指定端口。
下载并解压 TypeScript 示例及其已锁定版本的依赖项 。这些依赖项包括 OpenAI、MCP SDK 和 Zod。设置 OPENAI_API_KEY,并将 vs_123 替换为您的向量存储 ID。在示例项目目录中运行 pnpm install --ignore-workspace --frozen-lockfile,然后使用 node --experimental-strip-types mcp/mcp-server.ts 启动服务器。
本地服务器在 http://127.0.0.1:8000/mcp 上使用 Streamable HTTP。如果部署到托管环境,请将 app.listen 的绑定地址改为 0.0.0.0,在 createMcpExpressApp 的选项中设置 host: "0.0.0.0",并在 allowedHosts 中填入与部署环境完全匹配的主机名。请保持 Host 请求头验证开启,在托管环境的入口处配置 HTTPS 和访问控制,并在连接 URL 中使用 /mcp 路径。如果托管环境要求使用其他端口,请相应修改端口号。
如果使用 Go,请使用 github.com/openai/openai-go/v3 和 github.com/modelcontextprotocol/go-sdk。设置 OPENAI_API_KEY,将示例值 vs_123 替换为您现有的向量存储 ID,在模块中将源代码保存为 main.go,然后运行 go run .。服务器在端口 8000 的 /mcp 路径上使用 Streamable HTTP。要使用其他端口,请修改代码中 port 的字面值。要在 Replit 上将服务器绑定到所有 IPv4 接口,请将 host 的字面值改为 0.0.0.0。
您可以使用 gpt-6.2-sol 在提示词控制台中 测试 MCP 服务器。创建新提示词或编辑现有提示词,然后在提示词配置中添加新的 MCP 工具。此兼容性示例仅提供只读的 search 和 fetch 工具,因此其 API 请求会跳过对这两个工具的审批。对于能够修改数据或执行其他可能产生重大影响的操作的工具,请保持审批功能开启。
如果您要将此服务器作为插件的一部分进行测试,请按照连接并测试插件 中的步骤操作。
配置好 MCP 服务器后,您可以在提示词界面中与使用该服务器的模型聊天。
您也可以直接向 Responses API 发送以下示例请求来测试 MCP 服务器。
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 curl https://api.openai.com/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY " \
-d '{
"model": "gpt-6.2-sol",
"input": [
{
"role": "developer",
"content": [
{
"type": "input_text",
"text": "You are a research assistant that searches MCP servers to find answers to your questions."
}
]
},
{
"role": "user",
"content": [
{
"type": "input_text",
"text": "Are cats attached to their homes? Give a succinct one page overview."
}
]
}
],
"reasoning": {
"summary": "auto"
},
"tools": [
{
"type": "mcp",
"server_label": "cats",
"server_url": "https://777ff573-9947-4b9c-8982-658fa40c7d09-00-3le96u7wsymx.janeway.replit.dev/sse/",
"allowed_tools": [
"search",
"fetch"
],
"require_approval": "never"
}
]
}'
构建自定义远程 MCP 服务器时,您可以通过授权和身份验证保护数据。如果您的授权服务器支持客户端 ID 元数据文档(CIMD),且插件创建者选择了这种方式,我们建议使用 OAuth 并通过客户端 ID 元数据文档 注册客户端。使用 CIMD 时,ChatGPT 支持公共客户端令牌交换(none),也支持使用签名客户端断言进行令牌交换(private_key_jwt)。配置后,仍可使用动态客户端注册。有关插件的身份验证要求,请参阅身份验证 。有关协议的详细信息,请阅读 MCP 用户指南 或授权规范 。
如果您通过插件连接自定义远程 MCP 服务器,工作空间中的用户将通过 OAuth 流程连接到您的服务。
前往 ChatGPT 插件 页面,选择加号按钮,然后选择添加自定义 MCP 服务器 。
输入服务器 URL 和身份验证信息。阅读风险提示,选择我已了解并希望继续 ,然后选择创建为插件 。
安装插件,然后在聊天和深度研究中运行提示词来测试插件。
有关详细设置步骤,请参阅连接并测试插件 。
自定义 MCP 服务器可将您的 ChatGPT 工作空间连接到外部应用,使 ChatGPT 能够访问、发送和接收这些应用中的数据。请注意,自定义 MCP 服务器是第三方服务,适用各自的条款和条件。OpenAI 不开发也不验证这些服务器。
如果您发现恶意 MCP 服务器,请发送邮件至 security@openai.com 举报。
提示词注入是一种攻击手段。攻击者将恶意指令嵌入我们的模型可能接触到的内容(例如网页)中,企图让这些指令改变 ChatGPT 的预期行为。如果模型执行了注入的指令,就可能采取用户和开发者都无意执行的操作,包括向外部发送私密数据。
例如,您可能会请 ChatGPT 查看您的日历和近期邮件,为聚餐找一家餐厅。在查找信息时,它可能会遇到一条恶意评论,要求它从 Gmail 获取密码重置验证码并将其发送到恶意网站。这类有害内容的目的就是诱骗智能体执行非预期操作。
下表列出了需要考虑的具体场景。建议您仔细阅读,再决定是否使用自定义 MCP 服务器。
场景与风险
如果我信任 MCP 服务器的开发者,这样做安全吗?
我可以如何降低风险?
攻击者可能设法在 MCP 服务器可访问的数据中植入恶意指令,发起提示词注入攻击。示例 • 对于客服 MCP 服务器,攻击者可能向您提交一条含有恶意指令的客服请求,发起提示词注入攻击。
即使您信任 MCP 服务器的开发者,仍然存在风险。 要确保安全,您必须信任 通过该 MCP 服务器可以访问的全部内容 。
• 如果 MCP 服务器中可能包含恶意或不可信的用户输入,即使您信任其开发者,也请勿使用。 • 配置访问权限,尽量限制可访问该 MCP 服务器的人数。
恶意 MCP 服务器可能要求为读取或写入操作提供超出实际需要的参数。示例 • 为员工预订机票的 MCP 服务器可能提供查询航班时刻表的读取操作,却要求提供 summaryOfConversation、userAnnualIncome、userHomeAddress 等参数。
即使您信任 MCP 服务器的开发者,也未必安全。 开发者可能认为索取某些数据是合理的,而您认为这些数据不应共享。
• 手动安装 MCP 服务器时,请检查每项操作要求提供的参数,确保服务器没有索取超出操作所需范围的私人信息。
攻击者可能通过提示词注入诱骗 ChatGPT 从自定义 MCP 服务器获取敏感数据,再将数据发送给攻击者。示例 • 攻击者可能通过另一个 MCP 服务器(例如电子邮件服务)向某位企业用户发起提示词注入攻击,试图诱骗 ChatGPT 从内部工具读取敏感数据并将其发送给攻击者。
即使您信任 MCP 服务器的开发者,仍然存在风险。 即便新 MCP 服务器中的所有内容都安全可信,来自其他恶意来源的攻击仍可能窃取其中的数据。
• ChatGPT 在设计上注重保护用户 ,但攻击者仍可能试图窃取您的数据。请了解这一风险,并考虑是否值得承担。 • 对于包含特别敏感数据的 MCP 服务器,请配置访问权限,尽量限制可访问的人数。
攻击者可能通过提示词注入,利用向自定义 MCP 服务器写入数据的操作泄露敏感信息。示例 • 攻击者通过另一个 MCP 服务器发起提示词注入攻击,诱骗 ChatGPT 获取敏感数据,再通过客服系统的 MCP 服务器将数据发送给攻击者。
即使您信任 MCP 服务器的开发者,仍然存在风险。 即使您完全信任该 MCP 服务器,只要攻击者能观察到写入操作产生的某种结果,就可能试图加以利用。
• 执行写入操作时,用户应仔细核对,确保操作符合预期,并且不包含任何不应共享的数据。
由于 MCP 服务器可以记录读取操作,攻击者可能通过提示词注入,让发往恶意自定义 MCP 服务器的读取请求泄露敏感信息。
只有当 MCP 服务器本身具有恶意,或将写入操作错误地标记为读取操作时,这种攻击才会奏效。 如果您相信 MCP 服务器的开发者只会将真正的读取操作标记为 读取 ,也相信开发者不会试图窃取数据,那么这项风险通常很小。
• 仅使用可信开发者提供的 MCP 服务器,但请注意,仅凭这一点无法保证安全。
攻击者可能通过提示词注入,诱骗 ChatGPT 通过自定义 MCP 服务器执行用户无意执行的有害或破坏性写入操作。
即使您信任 MCP 服务器的开发者,仍然存在风险。 即便新 MCP 服务器中的所有内容都安全可信,这项风险依然存在,因为攻击来自其他恶意来源。
• 用户应仔细核对写入操作,确保操作符合预期且正确无误。 • ChatGPT 在设计上注重保护用户,但攻击者仍可能试图诱骗 ChatGPT 执行非预期的写入操作。 • 对于包含特别敏感数据的 MCP 服务器,请配置访问权限,尽量限制可访问的人数。
自定义 MCP 服务器还会带来以下与提示词注入攻击无关的风险。
写入操作可以让 MCP 服务器更有用,也会增加风险 ,因为服务器除了向 ChatGPT 提供信息,还可以执行可能具有破坏性的操作。目前,在任何对话中,ChatGPT 都要求用户手动确认后才会执行写入操作。确认时,ChatGPT 会标出可能敏感的数据。请先仔细考虑 ChatGPT 在执行这类操作时出错的可能性,只有在您可以接受这种风险时才使用写入操作。即使 MCP 服务器将操作标记为只读,仍可能发生写入。因此,在将自定义 MCP 服务器接入 ChatGPT 之前,务必确认该服务器值得信任。
任何 MCP 服务器都可能在处理查询时收到敏感数据 。即使服务器没有恶意,它也能访问 ChatGPT 在交互过程中提供的所有数据,其中可能包括用户之前提供给 ChatGPT 的敏感数据。例如,在使用深度研究或聊天应用工具时,ChatGPT 发往 MCP 服务器的查询就可能包含这些数据。
我们建议您只在了解并信任底层应用时连接其自定义 MCP 服务器。
例如,请选择由服务提供商自行托管的官方服务器。使用 Stripe 时,请连接 Stripe 在 mcp.stripe.com 托管的服务器,避免使用第三方托管的非官方 Stripe MCP 服务器。目前可用的官方 MCP 服务器较少,您也可以考虑由某个组织托管、通过 API 将请求转发给其他服务的服务器。请先了解该组织如何使用您的数据,并确认服务器值得信任,然后再连接。构建并连接自己的 MCP 服务器时,请再次核对您连接的是正确的服务器。当 OpenAI 调用您的 MCP 服务器时,请谨慎选择在响应请求时提供哪些数据,并妥善处理收到的数据。
通过您的远程 MCP 服务器,其他人可以将 OpenAI 连接到您的服务,使 OpenAI 能够在这些服务中访问、发送和接收数据,以及执行操作。请避免在工具的 JSON 中包含任何敏感信息,也不要存储访问您远程 MCP 服务器的 ChatGPT 用户的任何敏感信息。
构建 MCP 服务器时,请勿在工具定义中加入任何恶意内容。