mcp-csharp-debug

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

C# 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
    mcp.json
    or
    .mcp.json
    configuration
  • 首次在本地运行MCP服务器
  • 配置VS Code或Visual Studio调试MCP服务器
  • 使用MCP Inspector交互式测试工具
  • 验证工具在GitHub Copilot Agent Mode中正常展示
  • 诊断问题:工具未被发现、协议错误、服务崩溃
  • 配置
    mcp.json
    .mcp.json
    文件

Stop Signals

不适用提示

  • No project yet? → Use
    mcp-csharp-create
    first
  • Need automated tests? → Use
    mcp-csharp-test
  • Production deployment issue? → Use
    mcp-csharp-publish
  • 还没有项目? → 先使用
    mcp-csharp-create
    创建项目
  • 需要编写自动化测试? → 使用
    mcp-csharp-test
  • 遇到生产部署问题? → 使用
    mcp-csharp-publish

Inputs

输入参数

InputRequiredDescription
Project pathYesPath to the
.csproj
file or project directory
Transport typeRecommended
stdio
or
http
— detect from
.csproj
if not specified
IDERecommendedVS Code or Visual Studio — detect from environment if not specified
Agent behavior: Detect transport type by checking the
.csproj
for a
PackageReference
to
ModelContextProtocol.AspNetCore
. If present → HTTP, otherwise → stdio.
输入参数是否必填描述
项目路径
.csproj
文件或项目目录的路径
传输类型推荐
stdio
http
——如果未指定则从
.csproj
文件自动检测
IDE推荐VS Code或Visual Studio——如果未指定则从环境自动检测
Agent行为逻辑: 通过检查
.csproj
中是否存在
ModelContextProtocol.AspNetCore
PackageReference
来检测传输类型,如果存在则为HTTP,否则为stdio。

Workflow

操作流程

Step 1: Run the server locally

步骤1:本地运行服务器

stdio transport:
bash
cd <ProjectDir>
dotnet run
The 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 run
stdio传输:
bash
cd <ProjectDir>
dotnet run
进程启动后会等待stdin传入JSON-RPC消息,stdout没有输出就代表运行正常。
HTTP传输:
bash
cd <ProjectDir>
dotnet run

Server listens on http://localhost:3001 (or configured port)

undefined
undefined

Step 2: Generate MCP configuration

步骤2:生成MCP配置

Detect the IDE and transport, then create the appropriate config file.
For VS Code — create
.vscode/mcp.json
:
stdio:
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
.mcp.json
at solution root (same JSON structure).
For detailed IDE-specific configuration (launch.json, environment variables, secrets), see references/ide-config.md.
检测IDE和传输类型,然后创建对应的配置文件。
VS Code场景 — 创建
.vscode/mcp.json
stdio版本:
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场景 — 在解决方案根目录创建
.mcp.json
(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:
  1. Start your server:
    dotnet run
  2. Run Inspector:
    npx @modelcontextprotocol/inspector
  3. 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服务:
  1. 启动服务:
    dotnet run
  2. 运行Inspector:
    npx @modelcontextprotocol/inspector
  3. 连接到
    http://localhost:3001
如需查看Inspector的完整功能、使用方法和故障排查指南,请参考references/mcp-inspector.md

Step 4: Test with GitHub Copilot Agent Mode

步骤4:使用GitHub Copilot Agent Mode测试

  1. Open GitHub Copilot Chat → switch to Agent mode
  2. Click Select Tools (wrench icon) → verify your server and tools are listed
  3. Test with a prompt that should trigger your tool
  4. Approve tool execution when prompted
If tools don't appear — troubleshoot tool discovery:
  1. Rebuild first — stale builds are the #1 cause:
    bash
    dotnet build
    Then restart the MCP server (click Stop → Start in VS Code, or restart
    dotnet run
    ).
  2. Check attributes and registration:
    • Verify
      [McpServerToolType]
      on the class and
      [McpServerTool]
      on each public method
    • Methods can be
      static
      or instance (instance types need DI registration)
    • Verify
      .WithTools<T>()
      or
      .WithToolsFromAssembly()
      in Program.cs
  3. Check
    mcp.json
    points to the correct project path
  4. If still not appearing, reference the tool explicitly:
    Using #tool_name, do X
  1. 打开GitHub Copilot Chat → 切换到Agent模式
  2. 点击选择工具(扳手图标)→ 确认你的服务和工具已在列表中展示
  3. 输入可以触发你的工具的提示词进行测试
  4. 弹出工具执行授权提示时点击同意
如果工具没有展示——按以下步骤排查工具发现问题:
  1. 先重新构建项目——构建版本过旧是最常见的原因:
    bash
    dotnet build
    然后重启MCP服务器(在VS Code中点击停止→启动,或者重启
    dotnet run
    进程)。
  2. 检查属性和注册配置:
    • 确认类上添加了
      [McpServerToolType]
      注解,每个公共方法上添加了
      [McpServerTool]
      注解
    • 方法可以是
      static
      或者实例方法(实例类型需要完成DI注册)
    • 确认Program.cs中配置了
      .WithTools<T>()
      或者
      .WithToolsFromAssembly()
  3. 检查
    mcp.json
    中的项目路径是否正确
  4. 如果还是没有展示,可以显式引用工具:
    Using #tool_name, do X

Step 5: Set up breakpoint debugging

步骤5:配置断点调试

  1. Set breakpoints in your tool methods
  2. Launch with the debugger:
    • VS Code: F5 (requires
      launch.json
      — see references/ide-config.md)
    • Visual Studio: F5 or right-click project → Debug → Start
  3. Trigger the tool (via Inspector, Copilot, or test client)
  4. Execution pauses at breakpoints
Critical: Build in Debug configuration. Breakpoints won't hit in Release builds.
  1. 在你的工具方法中设置断点
  2. 带调试器启动:
    • VS Code: 按F5(需要配置
      launch.json
      ——参考references/ide-config.md
    • Visual Studio: 按F5或者右键项目→调试→启动调试
  3. 触发工具执行(通过Inspector、Copilot或者测试客户端)
  4. 执行会在断点处暂停
重要提示: 必须使用Debug配置构建,Release构建无法命中断点。

Diagnosing Tool Errors

工具错误诊断

When a tool works standalone but fails through MCP, work through these checks:
  1. 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.
  2. 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.
  3. 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>
  4. Check stdout contamination (stdio only) — Any
    Console.WriteLine()
    or logging to stdout corrupts the JSON-RPC protocol. Redirect all output to stderr (see Step 6).
  5. 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.
  6. Enable file logging — For post-mortem analysis, log to a file:
    csharp
    builder.Logging.AddFile("mcp-debug.log"); // or use Serilog/NLog
当工具单独运行正常但通过MCP调用失败时,可以按以下步骤排查:
  1. 检查MCP输出通道 — VS Code中:查看→输出→选择你的MCP服务名称,这里会展示协议错误和服务stderr输出。Visual Studio中:检查输出窗口中的MCP相关消息。
  2. 附加调试器 — 在报错的工具方法中设置断点,单步执行(参考步骤5),检查是否有被吞掉的异常或者不符合预期的参数值。
  3. 使用MCP Inspector测试 — 直接通过Inspector调用工具,定位问题是出在工具代码本身还是客户端集成:
    npx @modelcontextprotocol/inspector dotnet run --project <path>
  4. 检查stdout污染(仅stdio场景) — 任何
    Console.WriteLine()
    或者打印到stdout的日志都会破坏JSON-RPC协议,请将所有输出重定向到stderr(参考步骤6)。
  5. 检查常见问题:
    • 序列化错误 — 返回类型必须支持JSON序列化,避免循环引用。
    • DI注册问题 — 缺失服务注册会导致运行时异常,检查
      Program.cs
      配置。
    • 参数绑定问题 — 确保参数名称和类型与工具Schema匹配。
    • 未处理异常 — 用try-catch包裹工具逻辑,将日志打印到stderr或者文件中。
  6. 开启文件日志 — 用于事后分析,将日志写入文件:
    csharp
    builder.Logging.AddFile("mcp-debug.log"); // 也可以使用Serilog/NLog

Step 6: Configure logging

步骤6:配置日志

Critical for stdio transport: Any output to stdout (including
Console.WriteLine
) corrupts the MCP JSON-RPC protocol and causes garbled responses or crashes. All logging and diagnostic output must go to stderr.
stdio 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
ILogger<T>
via constructor and use
logger.LogDebug()
/
logger.LogError()
. Logging through
ILogger
respects the stderr configuration above.
stdio传输场景特别注意: 任何输出到stdout的内容(包括
Console.WriteLine
都会破坏MCP JSON-RPC协议,导致响应乱码或者服务崩溃,所有日志和诊断输出必须打印到stderr。
stdio传输 — 仅将日志打印到stderr:
csharp
builder.Logging.AddConsole(options =>
    options.LogToStandardErrorThreshold = LogLevel.Trace);
HTTP传输 — 日志配置参考references/ide-config.md
在工具方法中 — 通过构造函数注入
ILogger<T>
,使用
logger.LogDebug()
/
logger.LogError()
打印日志,通过
ILogger
打印的日志会自动遵循上面的stderr配置。

Validation

验证项

  • 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

常见陷阱

PitfallSolution
Tools not appearing or stale after changesRebuild first:
dotnet build
, then restart the server. If still missing, verify
[McpServerToolType]
on class,
[McpServerTool]
on methods, and
WithTools<T>()
or
WithToolsFromAssembly()
in Program.cs
stdio server produces garbled output
Console.WriteLine()
or logging is writing to stdout. All output must go to stderr. Set
LogToStandardErrorThreshold = LogLevel.Trace
on the console logger
HTTP server returns 404 at MCP endpointMissing
app.MapMcp()
in Program.cs
Breakpoints not hitBuilding in Release mode. Rebuild in Debug:
dotnet build -c Debug
, then restart
Environment variables not passed to serverAdd
"env"
section to
mcp.json
. For secrets in VS Code, use
"${input:var_id}"
syntax
MCP Inspector can't connect to HTTP serverServer not running, or wrong port. Check
dotnet run
output for the listening URL
陷阱解决方案
修改代码后工具不展示或者功能没有更新先重新构建: 执行
dotnet build
,然后重启服务。如果还是缺失,确认类上添加了
[McpServerToolType]
、方法上添加了
[McpServerTool]
,且Program.cs中配置了
WithTools<T>()
或者
WithToolsFromAssembly()
stdio服务输出乱码
Console.WriteLine()
或者日志打印到了stdout,所有输出必须打印到stderr,在控制台日志配置中设置
LogToStandardErrorThreshold = LogLevel.Trace
HTTP服务在MCP端点返回404Program.cs中缺失
app.MapMcp()
配置
无法命中断点使用了Release模式构建,切换到Debug模式重新构建:
dotnet build -c Debug
,然后重启服务
环境变量没有传递到服务
mcp.json
中添加
"env"
配置段,VS Code中使用密钥可以用
"${input:var_id}"
语法
MCP Inspector无法连接到HTTP服务服务未启动或者端口错误,检查
dotnet run
输出的监听URL

Related Skills

相关技能

  • mcp-csharp-create
    — Create a new MCP server project
  • mcp-csharp-test
    — Automated tests and evaluations
  • mcp-csharp-publish
    — NuGet, Docker, Azure deployment
  • mcp-csharp-create
    — 创建新的MCP服务器项目
  • mcp-csharp-test
    — 自动化测试和评估
  • mcp-csharp-publish
    — NuGet、Docker、Azure部署

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

更多信息