Conecte-se aos servidores MCP
Use ferramentas externas no bate-papo
O Protocolo de Contexto de Modelos (MCP) permite que grandes modelos de linguagem usem ferramentas externas e dados. Comparado com a função chamada, MCP oferece maior flexibilidade e facilidade de uso. Este tópico descreve como conectar-se ao MCP usando a API Responses.
Adicione informações do servidor MCP na tools parâmetro ao usar a API de Respostas.
Suporta servidores MCP usando o protocolo SSE. Máximo de 10 servidores MPC por pedido.
Começando.
Este exemplo usa o [recorte web da rede de busca] (https://modelscope.ai/mcp/servers/@modelcontextprotocol/fetch) Serviço MCP da ModelScope. Você pode obter a informação de SSE Endpoint e autenticação para o serviço na seção de configuração do Serviço à direita.
Pegue uma chave de API (/api-reference/preparation/api-key(configurando-o como uma variável de ambiente) (/api-reference/preparation/export-api-key-env).
Substituir server_url com o ponto final da SSE da plataforma de serviço MCP. Substitua a autenticação em headers com o símbolo fornecido por essa plataforma.
Python
```python
import os
from openai import OpenAI
client = OpenAI(
# If no environment variable, use: api_key="sk-xxx" (not recommended).
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://maas.qwencloudapi.com/compatible-mode/v1"
)
# MCP tool configuration
# Replace server_url with the SSE Endpoint that you got from a platform such as ModelScope
# If authentication is required, add the token from the corresponding platform to the headers
mcp_tool = {
"type": "mcp",
"server_protocol": "sse",
"server_label": "fetch",
"server_description": "Fetch MCP Server that provides web scraping capabilities. It can scrape the content of a specified URL and return it as text.",
"server_url": "https://mcp.api-inference.modelscope.net/xxx/sse",
}
response = client.responses.create(
model="qwen3.8-max",
input="https://news.aibase.com/zh/news, what is the AI news today?",
tools=[mcp_tool]
)
print("[Model Response]")
print(response.output_text)
print(f"\n[Token Usage] Input: {response.usage.input_tokens}, Output: {response.usage.output_tokens}, Total: {response.usage.total_tokens}")
```
Node.js
```javascript
import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
// If no environment variable, use: apiKey: "sk-xxx" (not recommended).
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://maas.qwencloudapi.com/compatible-mode/v1"
});
async function main() {
// MCP tool configuration
// Replace server_url with the SSE Endpoint that you got from a platform such as ModelScope
// If authentication is required, add the token from the corresponding platform to the headers
const mcpTool = {
type: "mcp",
server_protocol: "sse",
server_label: "fetch",
server_description: "Fetch MCP Server that provides web scraping capabilities. It can scrape the content of a specified URL and return it as text.",
server_url: "https://mcp.api-inference.modelscope.net/xxx/sse",
};
const response = await openai.responses.create({
model: "qwen3.8-max",
input: "https://news.aibase.com/zh/news, what is the AI news today?",
tools: [mcpTool]
});
console.log("[Model Response]");
console.log(response.output_text);
console.log(`\n[Token Usage] Input: ${response.usage.input_tokens}, Output: ${response.usage.output_tokens}, Total: ${response.usage.total_tokens}`);
}
main();
```
Java
```java expandable
// The QwenCloud MCP tool requires the server_protocol field, which the official OpenAI Java SDK's
// Tool.Mcp does not yet expose. Add it via putAdditionalProperty. JDK 8+ / Spring Boot 2.x compatible.
// Maven dependency: com.openai:openai-java:4.67.0 (or later)
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.*;
public class McpResponsesDemo {
public static void main(String[] args) {
// If no environment variable is set, replace the line below with: apiKey = "sk-xxx" (not recommended)
String apiKey = System.getenv("DASHSCOPE_API_KEY");
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(apiKey)
.baseUrl("https://maas.qwencloudapi.com/compatible-mode/v1")
.build();
// Replace server_url with the SSE Endpoint that you got from a platform such as ModelScope
// If authentication is required, add the token from the corresponding platform to the headers
Tool mcpTool = Tool.ofMcp(Tool.Mcp.builder()
.serverLabel("fetch")
.serverDescription("Fetch MCP Server that provides web scraping capabilities. It can scrape the content of a specified URL and return it as text.")
.serverUrl("https://mcp.api-inference.modelscope.net/xxx/sse")
.putAdditionalProperty("server_protocol", JsonValue.from("sse"))
.build());
ResponseCreateParams params = ResponseCreateParams.builder()
.model("qwen3.8-max")
.input("https://news.aibase.com/zh/news, what is the AI news today?")
.addTool(mcpTool)
.build();
// Call the Responses API
Response response = client.responses().create(params);
System.out.println("[Model Response]");
response.output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
response.usage().ifPresent(u ->
System.out.println("\n[Token Usage] Input: " + u.inputTokens()
+ ", Output: " + u.outputTokens()
+ ", Total: " + u.totalTokens()));
}
}
```
curl
```bash
# Replace server_url with the SSE Endpoint that you got from a platform such as ModelScope
# If authentication is required, add the token from the corresponding platform to the headers
curl -X POST https://maas.qwencloudapi.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-max",
"input": "https://news.aibase.com/zh/news, what is the AI news today?",
"tools": [
{
"type": "mcp",
"server_protocol": "sse",
"server_label": "fetch",
"server_description": "Fetch MCP Server that provides web scraping capabilities. It can scrape the content of a specified URL and return it as text.",
"server_url": "https://mcp.api-inference.modelscope.net/xxx/sse"
}
]
}'
```
Depois de executar o código, a resposta é devolvido:
[Model Response]
Based on the documentation for the Model Context Protocol (MCP) on the QwenCloud help center, the supported models are:
* Qwen Max:
* Qwen3.7-Max series
* Qwen Plus:
* Qwen3.6-Plus series
* Qwen3.5-Plus series
* Qwen Flash:
* Qwen3.8-Flash series
* Qwen3.7-Flash series
* Qwen3.6-Flash series
* Qwen3.5-Flash series
* Qwen3.6 Open Source Series (excluding qwen3.6-27b)
* Qwen3.5 Open Source Series
Note: The documentation specifies that MCP is only supported via the Responses API (client.responses.create) and not the standard Chat Completions API.
[Token Usage] Input: 20583, Output: 1638, Total: 22221
Saída de transmissão
Chamadas de ferramentas MCP podem envolver múltiplas interações com serviços externos. Habilitar transmissão para resultados intermediários em tempo real.
Python
```python
import os
from openai import OpenAI
client = OpenAI(
# If no environment variable, use: api_key="sk-xxx" (not recommended).
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://maas.qwencloudapi.com/compatible-mode/v1"
)
# Replace server_url with the SSE Endpoint that you got from a platform such as ModelScope
# If authentication is required, add the token from the corresponding platform to the headers
mcp_tool = {
"type": "mcp",
"server_protocol": "sse",
"server_label": "fetch",
"server_description": "Fetch MCP Server that provides web scraping capabilities. It can scrape the content of a specified URL and return it as text.",
"server_url": "https://mcp.api-inference.modelscope.net/xxx/sse",
}
stream = client.responses.create(
model="qwen3.8-max",
input="https://news.aibase.com/zh/news, what is the AI news today?",
tools=[mcp_tool],
stream=True
)
for event in stream:
# The model response starts
if event.type == "response.content_part.added":
print("[Model Response]")
# Streaming text output
elif event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
# The response is complete, output the usage
elif event.type == "response.completed":
usage = event.response.usage
print(f"\n\n[Token Usage] Input: {usage.input_tokens}, Output: {usage.output_tokens}, Total: {usage.total_tokens}")
```
Node.js
```javascript
import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
// If no environment variable, use: apiKey: "sk-xxx" (not recommended).
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://maas.qwencloudapi.com/compatible-mode/v1"
});
async function main() {
// Replace server_url with the SSE Endpoint that you got from a platform such as ModelScope
// If authentication is required, add the token from the corresponding platform to the headers
const mcpTool = {
type: "mcp",
server_protocol: "sse",
server_label: "fetch",
server_description: "Fetch MCP Server that provides web scraping capabilities. It can scrape the content of a specified URL and return it as text.",
server_url: "https://mcp.api-inference.modelscope.net/xxx/sse",
};
const stream = await openai.responses.create({
model: "qwen3.8-max",
input: "https://news.aibase.com/zh/news, what is the AI news today?",
tools: [mcpTool],
stream: true
});
for await (const event of stream) {
// The model response starts
if (event.type === "response.content_part.added") {
console.log("[Model Response]");
}
// Streaming text output
else if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
}
// The response is complete, output the usage
else if (event.type === "response.completed") {
const usage = event.response.usage;
console.log(`\n\n[Token Usage] Input: ${usage.input_tokens}, Output: ${usage.output_tokens}, Total: ${usage.total_tokens}`);
}
}
}
main();
```
Java
```java expandable
// The QwenCloud MCP tool requires the server_protocol field, which the official OpenAI Java SDK's
// Tool.Mcp does not yet expose. Add it via putAdditionalProperty. JDK 8+ / Spring Boot 2.x compatible.
// Maven dependency: com.openai:openai-java:4.67.0 (or later)
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.core.http.StreamResponse;
import com.openai.models.responses.*;
public class McpResponsesStreamDemo {
public static void main(String[] args) {
// If no environment variable is set, replace the line below with: apiKey = "sk-xxx" (not recommended)
String apiKey = System.getenv("DASHSCOPE_API_KEY");
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(apiKey)
.baseUrl("https://maas.qwencloudapi.com/compatible-mode/v1")
.build();
// Replace server_url with the SSE Endpoint that you got from a platform such as ModelScope
// If authentication is required, add the token from the corresponding platform to the headers
Tool mcpTool = Tool.ofMcp(Tool.Mcp.builder()
.serverLabel("fetch")
.serverDescription("Fetch MCP Server that provides web scraping capabilities. It can scrape the content of a specified URL and return it as text.")
.serverUrl("https://mcp.api-inference.modelscope.net/xxx/sse")
.putAdditionalProperty("server_protocol", JsonValue.from("sse"))
.build());
ResponseCreateParams params = ResponseCreateParams.builder()
.model("qwen3.8-max")
.input("https://news.aibase.com/zh/news, what is the AI news today?")
.addTool(mcpTool)
.build();
// Call the Responses API (streaming output)
System.out.println("[Model Response]");
try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {
stream.stream().forEach(event -> {
// Streaming text output
event.outputTextDelta().ifPresent(delta -> {
System.out.print(delta.delta());
System.out.flush();
});
// Response completed, print usage
if (event.isCompleted()) {
event.completed().ifPresent(completed ->
completed.response().usage().ifPresent(u ->
System.out.println("\n\n[Token Usage] Input: " + u.inputTokens()
+ ", Output: " + u.outputTokens()
+ ", Total: " + u.totalTokens())));
}
});
}
}
}
```
curl
```bash
# Replace server_url with the SSE Endpoint that you got from a platform such as ModelScope
# If authentication is required, add the token from the corresponding platform to the headers
curl -X POST https://maas.qwencloudapi.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-max",
"input": "https://news.aibase.com/zh/news, what is the AI news today?",
"tools": [
{
"type": "mcp",
"server_protocol": "sse",
"server_label": "fetch",
"server_description": "Fetch MCP Server that provides web scraping capabilities. It can scrape the content of a specified URL and return it as text.",
"server_url": "https://mcp.api-inference.modelscope.net/xxx/sse"
}
],
"stream": true
}'
```
Depois de executar o código, a resposta é devolvido:
[Model Response]
Based on the documentation page for MCP on QwenCloud, the following models are supported:
* Qwen Max Series: Qwen3.7-Max series
* Qwen Plus Series: Qwen3.6-Plus series and Qwen3.5-Plus series
* Qwen Flash Series: Qwen3.8-Flash series, Qwen3.7-Flash series, Qwen3.6-Flash series and Qwen3.5-Flash series
* Qwen3.6 Open Source Series (excluding qwen3.6-27b)
* Qwen3.5 Open Source Series
Note: These models support MCP functionality only via the Responses API.
[Token Usage] Input: 20472, Output: 945, Total: 21417
Parâmetros
O mcp A ferramenta suporta os seguintes parâmetros:
- Parâmetro requerido *
| -------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
typeSim, está pronto para"mcp". | |server_protocolSim, o protocolo de comunicação com o servidor MCP. Atualmente, só"sse"é apoiado. |server_labelSim, o nome do selo do servidor MCP, usado para identificar o serviço. |server_descriptionNão, uma descrição das características do servidor MCP. Isso ajuda o modelo a entender as capacidades e cenários do serviço. Preencher este parâmetro é recomendado para melhorar a precisão das chamadas de modelos. |server_urlSim, o URL do servidor MCP. |headers□ Não □ Os cabeçalhos de solicitação para incluir ao conectar-se ao servidor MCP, como informações de autenticação comoAuthorization. |
Exemplo:
{
"type": "mcp",
"server_protocol": "sse",
"server_label": "fetch",
"server_description": "Fetch MCP Server that provides web scraping capabilities. It can scrape the content of a specified URL and return it as text.",
"server_url": "https://mcp.api-inference.modelscope.net/xxx/sse"
}
Modelos apoiados.
MCP está disponível apenas através da API Responses.
- Qwen-Max: Qwen3.8-Max série, Qwen3.7-Max Série
- Qwen-Plus: Qwen3.7-Plus série, Qwen3.6-Plus série, Qwen3.5-Plus Série
- Qwen-Flash: qwen3.8-flash, Qwen3.7-Flash série, Qwen3.6-Flash série, Qwen3.5-Flash Série
- Qwen3.8 Série de código aberto
- Qwen3.6 Série de código aberto (excluindo qwen3.6-27b)
- Qwen3.5 Série de código aberto
Contagem
Dois tipos de cargas se aplicam quando se usa MCP:
- Taxa de inferência de modelos: faturada com base no uso do símbolo do modelo.
- Sujeito às regras de faturamento de cada provedor de servidor MCP.