mcp-csharp-debug
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseC# MCP Server Debugging
C# MCP 服务器调试
Run, debug, and interactively test C# MCP servers. Covers local execution, IDE debugging with breakpoints, MCP Inspector for protocol-level testing, and GitHub Copilot Agent Mode integration.
运行、调试并交互式测试C# MCP服务器,涵盖本地执行、带断点的IDE调试、用于协议级测试的MCP Inspector,以及GitHub Copilot Agent Mode集成。
When to Use
适用场景
- Running an MCP server locally for the first time
- Configuring VS Code or Visual Studio to debug an MCP server
- Testing tools interactively with MCP Inspector
- Verifying tools appear in GitHub Copilot Agent Mode
- Diagnosing issues: tools not discovered, protocol errors, server crashes
- Setting up or
mcp.jsonconfiguration.mcp.json
- 首次在本地运行MCP服务器
- 配置VS Code或Visual Studio调试MCP服务器
- 使用MCP Inspector交互式测试工具
- 验证工具在GitHub Copilot Agent Mode中正常展示
- 诊断问题:工具未被发现、协议错误、服务崩溃
- 配置或
mcp.json文件.mcp.json
Stop Signals
不适用提示
- No project yet? → Use first
mcp-csharp-create - Need automated tests? → Use
mcp-csharp-test - Production deployment issue? → Use
mcp-csharp-publish
- 还没有项目? → 先使用创建项目
mcp-csharp-create - 需要编写自动化测试? → 使用
mcp-csharp-test - 遇到生产部署问题? → 使用
mcp-csharp-publish
Inputs
输入参数
| Input | Required | Description |
|---|---|---|
| Project path | Yes | Path to the |
| Transport type | Recommended | |
| IDE | Recommended | VS Code or Visual Studio — detect from environment if not specified |
Agent behavior: Detect transport type by checking the for a to . If present → HTTP, otherwise → stdio.
.csprojPackageReferenceModelContextProtocol.AspNetCore| 输入参数 | 是否必填 | 描述 |
|---|---|---|
| 项目路径 | 是 | |
| 传输类型 | 推荐 | |
| IDE | 推荐 | VS Code或Visual Studio——如果未指定则从环境自动检测 |
Agent行为逻辑: 通过检查中是否存在的来检测传输类型,如果存在则为HTTP,否则为stdio。
.csprojModelContextProtocol.AspNetCorePackageReferenceWorkflow
操作流程
Step 1: Run the server locally
步骤1:本地运行服务器
stdio transport:
bash
cd <ProjectDir>
dotnet runThe process starts and waits for JSON-RPC messages on stdin. No output on stdout means it's working correctly.
HTTP transport:
bash
cd <ProjectDir>
dotnet runstdio传输:
bash
cd <ProjectDir>
dotnet run进程启动后会等待stdin传入JSON-RPC消息,stdout没有输出就代表运行正常。
HTTP传输:
bash
cd <ProjectDir>
dotnet runServer listens on http://localhost:3001 (or configured port)
undefinedundefinedStep 2: Generate MCP configuration
步骤2:生成MCP配置
Detect the IDE and transport, then create the appropriate config file.
For VS Code — create :
.vscode/mcp.jsonstdio:
json
{
"servers": {
"<ProjectName>": {
"type": "stdio",
"command": "dotnet",
"args": ["run", "--project", "<path/to/ProjectFile.csproj>"]
}
}
}HTTP:
json
{
"servers": {
"<ProjectName>": {
"type": "http",
"url": "http://localhost:3001"
}
}
}For Visual Studio — create at solution root (same JSON structure).
.mcp.jsonFor detailed IDE-specific configuration (launch.json, environment variables, secrets), see references/ide-config.md.
检测IDE和传输类型,然后创建对应的配置文件。
VS Code场景 — 创建:
.vscode/mcp.jsonstdio版本:
json
{
"servers": {
"<ProjectName>": {
"type": "stdio",
"command": "dotnet",
"args": ["run", "--project", "<path/to/ProjectFile.csproj>"]
}
}
}HTTP版本:
json
{
"servers": {
"<ProjectName>": {
"type": "http",
"url": "http://localhost:3001"
}
}
}Visual Studio场景 — 在解决方案根目录创建(JSON结构和上面相同)。
.mcp.json如需查看IDE专属的详细配置(launch.json、环境变量、密钥),请参考references/ide-config.md。
Step 3: Test with MCP Inspector
步骤3:使用MCP Inspector测试
The MCP Inspector provides a UI for testing tools, viewing schemas, and inspecting protocol messages.
stdio server:
bash
npx @modelcontextprotocol/inspector dotnet run --project <path/to/ProjectFile.csproj>HTTP server:
- Start your server:
dotnet run - Run Inspector:
npx @modelcontextprotocol/inspector - Connect to
http://localhost:3001
For detailed Inspector capabilities, usage, and troubleshooting, see references/mcp-inspector.md.
MCP Inspector提供了UI界面用于测试工具、查看Schema、检查协议消息。
stdio服务:
bash
npx @modelcontextprotocol/inspector dotnet run --project <path/to/ProjectFile.csproj>HTTP服务:
- 启动服务:
dotnet run - 运行Inspector:
npx @modelcontextprotocol/inspector - 连接到
http://localhost:3001
如需查看Inspector的完整功能、使用方法和故障排查指南,请参考references/mcp-inspector.md。
Step 4: Test with GitHub Copilot Agent Mode
步骤4:使用GitHub Copilot Agent Mode测试
- Open GitHub Copilot Chat → switch to Agent mode
- Click Select Tools (wrench icon) → verify your server and tools are listed
- Test with a prompt that should trigger your tool
- Approve tool execution when prompted
If tools don't appear — troubleshoot tool discovery:
-
Rebuild first — stale builds are the #1 cause:bash
dotnet buildThen restart the MCP server (click Stop → Start in VS Code, or restart).dotnet run -
Check attributes and registration:
- Verify on the class and
[McpServerToolType]on each public method[McpServerTool] - Methods can be or instance (instance types need DI registration)
static - Verify or
.WithTools<T>()in Program.cs.WithToolsFromAssembly()
- Verify
-
Checkpoints to the correct project path
mcp.json -
If still not appearing, reference the tool explicitly:
Using #tool_name, do X
- 打开GitHub Copilot Chat → 切换到Agent模式
- 点击选择工具(扳手图标)→ 确认你的服务和工具已在列表中展示
- 输入可以触发你的工具的提示词进行测试
- 弹出工具执行授权提示时点击同意
如果工具没有展示——按以下步骤排查工具发现问题:
-
先重新构建项目——构建版本过旧是最常见的原因:bash
dotnet build然后重启MCP服务器(在VS Code中点击停止→启动,或者重启进程)。dotnet run -
检查属性和注册配置:
- 确认类上添加了注解,每个公共方法上添加了
[McpServerToolType]注解[McpServerTool] - 方法可以是或者实例方法(实例类型需要完成DI注册)
static - 确认Program.cs中配置了或者
.WithTools<T>().WithToolsFromAssembly()
- 确认类上添加了
-
检查中的项目路径是否正确
mcp.json -
如果还是没有展示,可以显式引用工具:
Using #tool_name, do X
Step 5: Set up breakpoint debugging
步骤5:配置断点调试
- Set breakpoints in your tool methods
- Launch with the debugger:
- VS Code: F5 (requires — see references/ide-config.md)
launch.json - Visual Studio: F5 or right-click project → Debug → Start
- VS Code: F5 (requires
- Trigger the tool (via Inspector, Copilot, or test client)
- Execution pauses at breakpoints
Critical: Build in Debug configuration. Breakpoints won't hit in Release builds.
- 在你的工具方法中设置断点
- 带调试器启动:
- VS Code: 按F5(需要配置——参考references/ide-config.md)
launch.json - Visual Studio: 按F5或者右键项目→调试→启动调试
- VS Code: 按F5(需要配置
- 触发工具执行(通过Inspector、Copilot或者测试客户端)
- 执行会在断点处暂停
重要提示: 必须使用Debug配置构建,Release构建无法命中断点。
Diagnosing Tool Errors
工具错误诊断
When a tool works standalone but fails through MCP, work through these checks:
- Check the MCP output channel — In VS Code: View → Output → select your MCP server name. Shows protocol errors and server stderr. In Visual Studio: check the Output window for MCP-related messages.
- Attach a debugger — Set a breakpoint in the failing tool method and step through execution (see Step 5). Check for exceptions being swallowed or unexpected parameter values.
- Test with MCP Inspector — Call the tool directly through Inspector to isolate whether the issue is in the tool code or the client integration:
npx @modelcontextprotocol/inspector dotnet run --project <path> - Check stdout contamination (stdio only) — Any or logging to stdout corrupts the JSON-RPC protocol. Redirect all output to stderr (see Step 6).
Console.WriteLine() - Check common culprits:
- Serialization errors — Return types must be JSON-serializable. Avoid circular references.
- DI registration — Missing service registrations cause runtime exceptions. Check .
Program.cs - Parameter binding — Ensure parameter names and types match the tool schema.
- Unhandled exceptions — Wrap tool logic in try-catch and log to stderr or a file.
- Enable file logging — For post-mortem analysis, log to a file:
csharp
builder.Logging.AddFile("mcp-debug.log"); // or use Serilog/NLog
当工具单独运行正常但通过MCP调用失败时,可以按以下步骤排查:
- 检查MCP输出通道 — VS Code中:查看→输出→选择你的MCP服务名称,这里会展示协议错误和服务stderr输出。Visual Studio中:检查输出窗口中的MCP相关消息。
- 附加调试器 — 在报错的工具方法中设置断点,单步执行(参考步骤5),检查是否有被吞掉的异常或者不符合预期的参数值。
- 使用MCP Inspector测试 — 直接通过Inspector调用工具,定位问题是出在工具代码本身还是客户端集成:
npx @modelcontextprotocol/inspector dotnet run --project <path> - 检查stdout污染(仅stdio场景) — 任何或者打印到stdout的日志都会破坏JSON-RPC协议,请将所有输出重定向到stderr(参考步骤6)。
Console.WriteLine() - 检查常见问题:
- 序列化错误 — 返回类型必须支持JSON序列化,避免循环引用。
- DI注册问题 — 缺失服务注册会导致运行时异常,检查配置。
Program.cs - 参数绑定问题 — 确保参数名称和类型与工具Schema匹配。
- 未处理异常 — 用try-catch包裹工具逻辑,将日志打印到stderr或者文件中。
- 开启文件日志 — 用于事后分析,将日志写入文件:
csharp
builder.Logging.AddFile("mcp-debug.log"); // 也可以使用Serilog/NLog
Step 6: Configure logging
步骤6:配置日志
Critical for stdio transport: Any output to stdout (including ) corrupts the MCP JSON-RPC protocol and causes garbled responses or crashes. All logging and diagnostic output must go to stderr.
Console.WriteLinestdio transport — log to stderr only:
csharp
builder.Logging.AddConsole(options =>
options.LogToStandardErrorThreshold = LogLevel.Trace);HTTP transport — For HTTP transport logging configuration, see references/ide-config.md.
In tool methods — inject via constructor and use / . Logging through respects the stderr configuration above.
ILogger<T>logger.LogDebug()logger.LogError()ILoggerstdio传输场景特别注意: 任何输出到stdout的内容(包括)都会破坏MCP JSON-RPC协议,导致响应乱码或者服务崩溃,所有日志和诊断输出必须打印到stderr。
Console.WriteLinestdio传输 — 仅将日志打印到stderr:
csharp
builder.Logging.AddConsole(options =>
options.LogToStandardErrorThreshold = LogLevel.Trace);HTTP传输 — 日志配置参考references/ide-config.md。
在工具方法中 — 通过构造函数注入,使用 / 打印日志,通过打印的日志会自动遵循上面的stderr配置。
ILogger<T>logger.LogDebug()logger.LogError()ILoggerValidation
验证项
- Server starts without errors via
dotnet run - MCP Inspector connects and lists all expected tools
- Tool calls via Inspector return expected results
- Breakpoints hit when debugging in IDE
- Tools appear in GitHub Copilot Agent Mode tool list
- stdio: no logging output on stdout (stderr only)
- 执行后服务正常启动无报错
dotnet run - MCP Inspector可以成功连接并展示所有预期的工具
- 通过Inspector调用工具返回预期结果
- IDE调试时可以正常命中断点
- 工具在GitHub Copilot Agent Mode的工具列表中正常展示
- stdio场景:stdout没有日志输出(仅stderr有输出)
Common Pitfalls
常见陷阱
| Pitfall | Solution |
|---|---|
| Tools not appearing or stale after changes | Rebuild first: |
| stdio server produces garbled output | |
| HTTP server returns 404 at MCP endpoint | Missing |
| Breakpoints not hit | Building in Release mode. Rebuild in Debug: |
| Environment variables not passed to server | Add |
| MCP Inspector can't connect to HTTP server | Server not running, or wrong port. Check |
| 陷阱 | 解决方案 |
|---|---|
| 修改代码后工具不展示或者功能没有更新 | 先重新构建: 执行 |
| stdio服务输出乱码 | |
| HTTP服务在MCP端点返回404 | Program.cs中缺失 |
| 无法命中断点 | 使用了Release模式构建,切换到Debug模式重新构建: |
| 环境变量没有传递到服务 | 在 |
| MCP Inspector无法连接到HTTP服务 | 服务未启动或者端口错误,检查 |
Related Skills
相关技能
- — Create a new MCP server project
mcp-csharp-create - — Automated tests and evaluations
mcp-csharp-test - — NuGet, Docker, Azure deployment
mcp-csharp-publish
- — 创建新的MCP服务器项目
mcp-csharp-create - — 自动化测试和评估
mcp-csharp-test - — NuGet、Docker、Azure部署
mcp-csharp-publish
Reference Files
参考文件
- references/mcp-inspector.md — Detailed MCP Inspector usage: installation, connecting to servers, feature walkthrough, troubleshooting. Load when: user needs detailed Inspector guidance or is having connection issues.
- references/ide-config.md — Complete VS Code and Visual Studio configuration: mcp.json templates, launch.json, environment variables, conditional breakpoints. Load when: setting up IDE debugging or configuring environment-specific settings.
- references/mcp-inspector.md — MCP Inspector详细使用指南:安装、连接服务、功能介绍、故障排查。加载场景: 用户需要详细的Inspector使用指导或者遇到连接问题时。
- references/ide-config.md — VS Code和Visual Studio完整配置:mcp.json模板、launch.json、环境变量、条件断点。加载场景: 配置IDE调试或者环境专属设置时。
More Info
更多信息
- MCP Inspector — Interactive debugging tool for MCP servers
- VS Code MCP documentation — Configuring MCP servers in VS Code
- MCP Inspector — MCP服务器交互式调试工具
- VS Code MCP 文档 — VS Code中配置MCP服务器的指南