MCP 入门
欢迎开始使用模型上下文协议 (MCP)!无论您是 MCP 新手还是希望深入了解,本指南都将引导您完成必要的设置和开发流程。您将了解 MCP 如何实现 AI 模型与应用程序之间的无缝集成,并学习如何快速准备好您的环境,以构建和测试由 MCP 驱动的解决方案。
简而言之:如果您开发过 AI 应用,您就会知道可以向 LLM(大型语言模型)添加工具和其他资源,以增强 LLM 的知识储备。但是,如果您将这些工具和资源放在服务器上,那么无论是否拥有 LLM,任何客户端都可以使用该应用和服务器功能。
概述
本课程提供搭建 MCP 环境和构建首个 MCP 应用的实用指导。您将学习如何设置必要的工具和框架、构建基本的 MCP 服务器、创建主机应用以及测试您的实现。
模型上下文协议 (MCP) 是一种开放协议,它规范了应用程序向 LLM 提供上下文的方式。MCP 就像 AI 应用程序的 USB-C 端口,它提供了一种标准化的方式,将 AI 模型连接到不同的数据源和工具。
学习目标
学完本课后,您将能够:
- 使用 C#、Java、Python、TypeScript 和 JavaScript 设置 MCP 开发环境
- 构建和部署具有自定义功能(资源、提示和工具)的基本 MCP 服务器
- 创建连接到 MCP 服务器的主机应用程序
- 测试和调试 MCP 实现
设置您的 MCP 环境
在开始使用 MCP 之前,务必准备好开发环境并了解基本工作流程。本部分将指导您完成初始设置步骤,确保您顺利开始使用 MCP。
先决条件
在深入 MCP 开发之前,请确保您已:
- 开发环境:针对您选择的语言(C#、Java、Python、TypeScript 或 JavaScript)
- IDE/编辑器:Visual Studio、Visual Studio Code、IntelliJ、Eclipse、PyCharm 或任何现代代码编辑器
- 软件包管理器:NuGet、Maven/Gradle、pip 或 npm/yarn
- API 密钥:适用于您计划在主机应用程序中使用的任何 AI 服务
MCP 服务器基本结构
MCP 服务器通常包括:
- 服务器配置:设置端口、身份验证和其他设置
- 资源:向法学硕士提供的数据和背景
- 工具:模型可以调用的功能
- 提示:用于生成或构建文本的模板
以下是 TypeScript 中的一个简化示例:
import { Server, Tool, Resource } from "@modelcontextprotocol/typescript-server-sdk";
// Create a new MCP server
const server = new Server({
port: 3000,
name: "Example MCP Server",
version: "1.0.0"
});
// Register a tool
server.registerTool({
name: "calculator",
description: "Performs basic calculations",
parameters: {
expression: {
type: "string",
description: "The math expression to evaluate"
}
},
handler: async (params) => {
const result = eval(params.expression);
return { result };
}
});
// Start the server
server.start();
在上面的代码中我们:
- 从 MCP TypeScript SDK 导入必要的类。
- 创建并配置新的 MCP 服务器实例。
calculator
使用处理程序函数注册自定义工具( )。- 启动服务器来监听传入的 MCP 请求。
测试和调试
在开始测试 MCP 服务器之前,务必了解可用的调试工具和最佳实践。有效的测试可确保您的服务器正常运行,并帮助您快速识别和解决问题。以下部分概述了验证 MCP 实现的推荐方法。
MCP 提供了帮助您测试和调试服务器的工具:
- 检查器工具,这个图形界面允许您连接到您的服务器并测试您的工具、提示和资源。
- curl,您还可以使用命令行工具(如 curl 或其他可以创建和运行 HTTP 命令的客户端)连接到您的服务器。
使用 MCP 检查器
MCP Inspector是一款可视化测试工具,可帮助您:
- 发现服务器功能:自动检测可用资源、工具和提示
- 测试工具执行:尝试不同的参数并实时查看响应
- 查看服务器元数据:检查服务器信息、模式和配置
# ex TypeScript, installing and running MCP Inspector
npx @modelcontextprotocol/inspector node build/index.js
运行上述命令后,MCP Inspector 会在您的浏览器中启动一个本地 Web 界面。您将看到一个仪表板,其中显示您已注册的 MCP 服务器及其可用的工具、资源和提示。该界面允许您以交互方式测试工具的执行情况、检查服务器元数据并查看实时响应,从而更轻松地验证和调试您的 MCP 服务器实现。
以下是它的屏幕截图:
常见设置问题及解决方案
问题 | 可能的解决方案 |
---|---|
连接被拒绝 | 检查服务器是否正在运行并且端口是否正确 |
工具执行错误 | 检查参数验证和错误处理 |
身份验证失败 | 验证 API 密钥和权限 |
架构验证错误 | 确保参数与定义的模式匹配 |
服务器未启动 | 检查端口冲突或缺少依赖项 |
CORS 错误 | 为跨域请求配置适当的 CORS 标头 |
身份验证问题 | 验证令牌有效性和权限 |
本地开发
对于本地开发和测试,您可以直接在您的机器上运行 MCP 服务器:
- 启动服务器进程:运行 MCP 服务器应用程序
- 配置网络:确保服务器可在预期端口上访问
- 连接客户端:使用本地连接 URL,例如
http://localhost:3000
# Example: Running a TypeScript MCP server locally
npm run start
# Server running at http://localhost:3000
构建您的第一个 MCP 服务器
我们在上一课中已经讲解了核心概念,现在是时候将这些知识付诸实践了。
服务器可以做什么
在开始编写代码之前,让我们先回顾一下服务器可以做什么:
例如,MCP 服务器可以:
- 访问本地文件和数据库
- 连接到远程 API
- 执行计算
- 与其他工具和服务集成
- 提供用于交互的用户界面
太好了,现在我们知道可以做什么了,让我们开始编码吧。
练习:创建服务器
要创建服务器,您需要遵循以下步骤:
- 安装 MCP SDK。
- 创建一个项目并设置项目结构。
- 编写服务器代码。
- 测试服务器。
-1- 安装 SDK
这取决于您选择的运行时,因此请选择以下运行时之一:
生成式人工智能可以生成文本、图像甚至代码。
TypeScript
npm install @modelcontextprotocol/sdk zod
npm install -D @types/node typescript
Python
# For server development
pip install "mcp[cli]"
dotnet add package ModelContextProtocol --prerelease
dotnet add package Microsoft.Extensions.Hosting
Java
对于 Java,创建一个 Spring Boot 项目:
curl https://start.spring.io/starter.zip \
-d dependencies=web \
-d javaVersion=21 \
-d type=maven-project \
-d groupId=com.example \
-d artifactId=calculator-server \
-d name=McpServer \
-d packageName=com.microsoft.mcp.sample.server \
-o calculator-server.zip
解压 zip 文件:
unzip calculator-server.zip -d calculator-server
cd calculator-server
# optional remove the unused test
rm -rf src/test/java
将以下完整配置添加到您的pom.xml文件中:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- Spring Boot parent for dependency management -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.0</version>
<relativePath />
</parent>
<!-- Project coordinates -->
<groupId>com.example</groupId>
<artifactId>calculator-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Calculator Server</name>
<description>Basic calculator MCP service for beginners</description>
<!-- Properties -->
<properties>
<java.version>21</java.version>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
</properties>
<!-- Spring AI BOM for version management -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.0-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!-- Dependencies -->
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<!-- Build configuration -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<release>21</release>
</configuration>
</plugin>
</plugins>
</build>
<!-- Repositories for Spring AI snapshots -->
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
</project>
-2- 创建项目
现在您已经安装了 SDK,接下来让我们创建一个项目:
TypeScript
mkdir src
npm install -y
Python
python -m venv venv
venv\Scripts\activate
cd calculator-server
./mvnw clean install -DskipTests
-3- 创建项目文件
TypeScript
创建包含以下内容的package.json :
{
"type": "module",
"bin": {
"weather": "./build/index.js"
},
"scripts": {
"build": "tsc && node build/index.js"
},
"files": [
"build"
]
}
创建包含以下内容的tsconfig.json :
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"outDir": "./build",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
.Net
dotnet new console
Python
创建文件server.py
Java
对于 Java Spring Boot 项目,项目结构会自动创建。
-4- 创建服务器代码
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
// Create an MCP server
const server = new McpServer({
name: "Demo",
version: "1.0.0"
});
Python
# server.py
from mcp.server.fastmcp import FastMCP
# Create an MCP server
mcp = FastMCP("Demo")
.Net
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using System.ComponentModel;
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(consoleLogOptions =>
{
// Configure all logs to go to stderr
consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
});
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();
// add features
对于 Java,创建核心服务器组件。首先,修改主应用程序类:
src/main/java/com/microsoft/mcp/sample/server/McpServerApplication.java:
package com.microsoft.mcp.sample.server;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.method.MethodToolCallbackProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.microsoft.mcp.sample.server.service.CalculatorService;
@SpringBootApplication
public class McpServerApplication {
public static void main(String[] args) {
SpringApplication.run(McpServerApplication.class, args);
}
@Bean
public ToolCallbackProvider calculatorTools(CalculatorService calculator) {
return MethodToolCallbackProvider.builder().toolObjects(calculator).build();
}
}
创建计算器服务src/main/java/com/microsoft/mcp/sample/server/service/CalculatorService.java:
package com.microsoft.mcp.sample.server.service;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.stereotype.Service;
/**
* Service for basic calculator operations.
* This service provides simple calculator functionality through MCP.
*/
@Service
public class CalculatorService {
/**
* Add two numbers
* @param a The first number
* @param b The second number
* @return The sum of the two numbers
*/
@Tool(description = "Add two numbers together")
public String add(double a, double b) {
double result = a + b;
return formatResult(a, "+", b, result);
}
/**
* Subtract one number from another
* @param a The number to subtract from
* @param b The number to subtract
* @return The result of the subtraction
*/
@Tool(description = "Subtract the second number from the first number")
public String subtract(double a, double b) {
double result = a - b;
return formatResult(a, "-", b, result);
}
/**
* Multiply two numbers
* @param a The first number
* @param b The second number
* @return The product of the two numbers
*/
@Tool(description = "Multiply two numbers together")
public String multiply(double a, double b) {
double result = a * b;
return formatResult(a, "*", b, result);
}
/**
* Divide one number by another
* @param a The numerator
* @param b The denominator
* @return The result of the division
*/
@Tool(description = "Divide the first number by the second number")
public String divide(double a, double b) {
if (b == 0) {
return "Error: Cannot divide by zero";
}
double result = a / b;
return formatResult(a, "/", b, result);
}
/**
* Calculate the power of a number
* @param base The base number
* @param exponent The exponent
* @return The result of raising the base to the exponent
*/
@Tool(description = "Calculate the power of a number (base raised to an exponent)")
public String power(double base, double exponent) {
double result = Math.pow(base, exponent);
return formatResult(base, "^", exponent, result);
}
/**
* Calculate the square root of a number
* @param number The number to find the square root of
* @return The square root of the number
*/
@Tool(description = "Calculate the square root of a number")
public String squareRoot(double number) {
if (number < 0) {
return "Error: Cannot calculate square root of a negative number";
}
double result = Math.sqrt(number);
return String.format("√%.2f = %.2f", number, result);
}
/**
* Calculate the modulus (remainder) of division
* @param a The dividend
* @param b The divisor
* @return The remainder of the division
*/
@Tool(description = "Calculate the remainder when one number is divided by another")
public String modulus(double a, double b) {
if (b == 0) {
return "Error: Cannot divide by zero";
}
double result = a % b;
return formatResult(a, "%", b, result);
}
/**
* Calculate the absolute value of a number
* @param number The number to find the absolute value of
* @return The absolute value of the number
*/
@Tool(description = "Calculate the absolute value of a number")
public String absolute(double number) {
double result = Math.abs(number);
return String.format("|%.2f| = %.2f", number, result);
}
/**
* Get help about available calculator operations
* @return Information about available operations
*/
@Tool(description = "Get help about available calculator operations")
public String help() {
return "Basic Calculator MCP Service\n\n" +
"Available operations:\n" +
"1. add(a, b) - Adds two numbers\n" +
"2. subtract(a, b) - Subtracts the second number from the first\n" +
"3. multiply(a, b) - Multiplies two numbers\n" +
"4. divide(a, b) - Divides the first number by the second\n" +
"5. power(base, exponent) - Raises a number to a power\n" +
"6. squareRoot(number) - Calculates the square root\n" +
"7. modulus(a, b) - Calculates the remainder of division\n" +
"8. absolute(number) - Calculates the absolute value\n\n" +
"Example usage: add(5, 3) will return 5 + 3 = 8";
}
/**
* Format the result of a calculation
*/
private String formatResult(double a, String operator, double b, double result) {
return String.format("%.2f %s %.2f = %.2f", a, operator, b, result);
}
}
生产就绪服务的可选组件:
创建启动配置src/main/java/com/microsoft/mcp/sample/server/config/StartupConfig.java:
package com.microsoft.mcp.sample.server.config;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class StartupConfig {
@Bean
public CommandLineRunner startupInfo() {
return args -> {
System.out.println("\n" + "=".repeat(60));
System.out.println("Calculator MCP Server is starting...");
System.out.println("SSE endpoint: http://localhost:8080/sse");
System.out.println("Health check: http://localhost:8080/actuator/health");
System.out.println("=".repeat(60) + "\n");
};
}
}
创建健康控制器src/main/java/com/microsoft/mcp/sample/server/controller/HealthController.java:
package com.microsoft.mcp.sample.server.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@RestController
public class HealthController {
@GetMapping("/health")
public ResponseEntity<Map<String, Object>> healthCheck() {
Map<String, Object> response = new HashMap<>();
response.put("status", "UP");
response.put("timestamp", LocalDateTime.now().toString());
response.put("service", "Calculator MCP Server");
return ResponseEntity.ok(response);
}
}
创建异常处理程序src/main/java/com/microsoft/mcp/sample/server/exception/GlobalExceptionHandler.java:
package com.microsoft.mcp.sample.server.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<ErrorResponse> handleIllegalArgumentException(IllegalArgumentException ex) {
ErrorResponse error = new ErrorResponse(
"Invalid_Input",
"Invalid input parameter: " + ex.getMessage());
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
public static class ErrorResponse {
private String code;
private String message;
public ErrorResponse(String code, String message) {
this.code = code;
this.message = message;
}
// Getters
public String getCode() { return code; }
public String getMessage() { return message; }
}
}v
创建自定义横幅src/main/resources/banner.txt:
_____ _ _ _
/ ____| | | | | | |
| | __ _| | ___ _ _| | __ _| |_ ___ _ __
| | / _` | |/ __| | | | |/ _` | __/ _ \| '__|
| |___| (_| | | (__| |_| | | (_| | || (_) | |
\_____\__,_|_|\___|\__,_|_|\__,_|\__\___/|_|
Calculator MCP Server v1.0
Spring Boot MCP Application
-5- 添加工具和资源
通过添加以下代码来添加工具和资源:
TypeScript server.tool("add",
{ a: z.number(), b: z.number() },
async ({ a, b }) => ({
content: [{ type: "text", text: String(a + b) }]
})
);
server.resource(
"greeting",
new ResourceTemplate("greeting://{name}", { list: undefined }),
async (uri, { name }) => ({
contents: [{
uri: uri.href,
text: `Hello, ${name}!`
}]
})
);
您的工具接受参数a
并b
运行在表单上产生响应的函数:
{
contents: [{
type: "text", content: "some content"
}]
}
您的资源通过字符串“greeting”进行访问,并采用参数name
并产生与工具类似的响应:
{
uri: "<href>",
text: "a text"
}
Python
# Add an addition tool
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
# Add a dynamic greeting resource
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Get a personalized greeting"""
return f"Hello, {name}!"
在上面的代码中我们:
- 定义了一个
add
接受参数a
和的工具p
,这两个参数都是整数。 greeting
创建了一个名为并接受参数 的资源name
。
[McpServerToolType]
public static class CalculatorTool
{
[McpServerTool, Description("Adds two numbers")]
public static string Add(int a, int b) => $"Sum {a + b}";
}
这些工具已在上一步中创建。
-6 最终代码
让我们添加所需的最后代码以便服务器可以启动:
TypeScript// Start receiving messages on stdin and sending messages on stdout
const transport = new StdioServerTransport();
await server.connect(transport);
以下是完整代码:
// index.ts
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
// Create an MCP server
const server = new McpServer({
name: "Demo",
version: "1.0.0"
});
// Add an addition tool
server.tool("add",
{ a: z.number(), b: z.number() },
async ({ a, b }) => ({
content: [{ type: "text", text: String(a + b) }]
})
);
// Add a dynamic greeting resource
server.resource(
"greeting",
new ResourceTemplate("greeting://{name}", { list: undefined }),
async (uri, { name }) => ({
contents: [{
uri: uri.href,
text: `Hello, ${name}!`
}]
})
);
// Start receiving messages on stdin and sending messages on stdout
const transport = new StdioServerTransport();
await server.connect(transport);
# server.py
from mcp.server.fastmcp import FastMCP
# Create an MCP server
mcp = FastMCP("Demo")
# Add an addition tool
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
# Add a dynamic greeting resource
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Get a personalized greeting"""
return f"Hello, {name}!"
<span style="background-color:#151b23"><span style="color:#f0f6fc"><span style="background-color:#151b23"><code>using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using System.ComponentModel;
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(consoleLogOptions =>
{
// Configure all logs to go to stderr
consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
});
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();
[McpServerToolType]
public static class CalculatorTool
{
[McpServerTool, Description("Adds two numbers")]
public static string Add(int a, int b) => $"Sum {a + b}";
}
</code></span></span></span>
您的完整主应用程序类应如下所示:
// McpServerApplication.java
package com.microsoft.mcp.sample.server;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.method.MethodToolCallbackProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.microsoft.mcp.sample.server.service.CalculatorService;
@SpringBootApplication
public class McpServerApplication {
public static void main(String[] args) {
SpringApplication.run(McpServerApplication.class, args);
}
@Bean
public ToolCallbackProvider calculatorTools(CalculatorService calculator) {
return MethodToolCallbackProvider.builder().toolObjects(calculator).build();
}
}
-7- 测试服务器
使用以下命令启动服务器
Typescript
npm run build
Python
mcp run server.py
.NET
dotnet run
Java
./mvnw clean install -DskipTests
java -jar target/calculator-server-0.0.1-SNAPSHOT.jar
-8- (使用检查器运行)Run using the inspector
检查器(inspector),它可以启动你的服务器并允许你与之交互,以便测试它是否正常工作。让我们启动它:
Note
it might look different in the "command" field as it contains the command for running a server with your specific runtime/
TypeScript
npx @modelcontextprotocol/inspector node build/index.js
或者像这样将其添加到你的package.json "inspector": "npx @modelcontextprotocol/inspector node build/index.js"
中:然后运行 npm run inspect
Python
Python 封装了一个名为 inspector 的 Node.js 工具。可以像这样调用该工具:
mcp dev server.py
.NET
npx @modelcontextprotocol/inspector dotnet run
Java
确保计算器服务器正在运行,运行检查器:
npx @modelcontextprotocol/inspector
在检查器 Web 界面中:
- 选择“SSE”作为传输类型
- 将 URL 设置为:
http://localhost:8080/sse
- 点击“连接”

您现在已连接到服务器 Java 服务器测试部分现已完成
下一节是关于与服务器交互。

- 通过选择“连接”按钮连接到服务器一旦连接到服务器,您现在应该看到以下内容:
- 选择“Tools”和“listTools”,您应该会看到“添加”出现,选择“添加”并填写参数值。
您应该看到以下响应,即来自“添加”工具的结果:
恭喜,您已成功创建并运行您的第一台服务器!
官方 SDK
MCP 提供多种语言的官方 SDK:
- C# SDK - 与 Microsoft 合作维护
- Java SDK - 与 Spring AI 合作维护
- TypeScript SDK - 官方 TypeScript 实现
- Python SDK——官方 Python 实现
- Kotlin SDK - 官方 Kotlin 实现
- Swift SDK - 与 Loopwork AI 合作维护
- Rust SDK - Rust 官方实现
关键要点
- 使用特定语言的 SDK 可以轻松设置 MCP 开发环境
- 构建 MCP 服务器涉及创建和注册具有清晰架构的工具
- 测试和调试对于可靠的 MCP 实现至关重要
示例
任务
使用您选择的工具创建一个简单的 MCP 服务器:
- 使用您喜欢的语言(.NET、Java、Python 或 JavaScript)实现该工具。
- 定义输入参数和返回值。
- 运行检查工具以确保服务器按预期工作。
- 使用各种输入测试实现情况。