MCP Debugging with MCP Inspector and MCP Security Risks

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 9 min read🎯 D8 MCP Server Development and Integration · D7 Prompt Injection and Jailbreak Defense

👋 In plain words: When an MCP server does not work, the cause is usually one of a few things: it does not start, it writes junk into the protocol channel, it fails to authenticate, or its tools confuse the model. And because MCP connects Claude to real systems, a bad or malicious server is a security risk. This lesson covers both, step by step.

Advertisement

MCP failures are frustrating because the host often reports only “server disconnected” or “failed to connect”. In this lesson you will build a debugging routine: check the server starts, explore it with the MCP Inspector, log to stderr, reproduce and fix the classic stdout-corruption bug, separate protocol errors from tool errors, and then work through the main MCP security risks with a mitigation for each.

📖 What You’ll Learn: You will be able to diagnose MCP connection, protocol, tool and auth failures, use the MCP Inspector and stderr logging, and identify and mitigate MCP security risks such as tool poisoning, injected tool results and over-broad permissions.

🔑 Key terms

  • MCP Inspector: a browser-based tool for connecting to an MCP server and calling its tools by hand.
  • Protocol error: a JSON-RPC error (unknown method, malformed message); the request failed at the protocol level.
  • Tool error: a normal result with is_error true; the tool ran and reported a problem.
  • Tool poisoning: a malicious or careless tool description that contains instructions for the model.
  • Confused deputy: a server that uses its own powerful credentials on behalf of a caller who should not have that power.

🪜 Step 1: Check that the server starts at all

Most “MCP server failed to connect” reports are start-up problems. Run the exact command the host runs, in a plain terminal:

⌨️ Terminal

python C:\tools\qa_server.py

A healthy stdio server prints nothing and waits for input (press Ctrl+C to stop it). An import error, a missing package or a wrong path shows up immediately as a traceback. Typical causes:

  1. Different Python: the host starts python from its own PATH, not your virtual environment. Use the full path to the venv’s Python in the host config.
  2. Relative paths: the host’s working directory is not your project folder. Use absolute paths.
  3. Missing environment variables: tokens set in your shell are not set for the host. Pass them in the server’s env configuration.

🪜 Step 2: Explore it with the MCP Inspector

The Inspector connects to your server and shows its tools, resources and prompts, and lets you call them with your own arguments. The Python SDK’s CLI starts it for you (it runs the Inspector with Node.js):

⌨️ Terminal

mcp dev qa_server.py

Use it to answer three questions quickly: does the tool list look right, do the schemas match what you expect, and does each tool return what you expect for good and bad inputs?

Advertisement

🪜 Step 3: Log to stderr, never stdout

With stdio, stdout is the protocol channel. Any stray output there corrupts the JSON-RPC stream. This server has a debugging print() at start-up:

📄 noisy_server.py

from mcp.server.mcpserver import MCPServer

print("starting qa server...")  # BUG: goes to stdout, the protocol channel
mcp = MCPServer("noisy")


@mcp.tool()
def ping() -> str:
    """Health check."""
    return "pong"


if __name__ == "__main__":
    mcp.run()

📄 fixed_server.py

import logging
import sys

from mcp.server.mcpserver import MCPServer

logging.basicConfig(stream=sys.stderr, level=logging.INFO)  # logs go to stderr
log = logging.getLogger("qa-server")
log.info("starting qa server...")
mcp = MCPServer("fixed")


@mcp.tool()
def ping() -> str:
    """Health check."""
    log.info("ping called")
    return "pong"


if __name__ == "__main__":
    mcp.run()

📄 compare.py

import asyncio
import subprocess
import sys

from mcp import Client, StdioServerParameters


async def try_server(script: str) -> None:
    params = StdioServerParameters(command=sys.executable, args=[script])
    try:
        async with Client(params, read_timeout_seconds=10) as client:
            result = await client.call_tool("ping", {})
            print(f"{script}: OK -> {result.content[0].text}")
    except BaseException as e:  # the SDK raises an ExceptionGroup on a broken session
        print(f"{script}: FAILED ({type(e).__name__})")


asyncio.run(try_server("fixed_server.py"))
out = subprocess.run([sys.executable, "noisy_server.py"], input="", capture_output=True, text=True, timeout=20)
print("noisy_server.py wrote to stdout before any protocol message:", repr(out.stdout.splitlines()[0]))

⌨️ Terminal

python compare.py

🖥️ Output

fixed_server.py: OK -> pong
noisy_server.py wrote to stdout before any protocol message: 'starting qa server...'
INFO:qa-server:starting qa server...
INFO:qa-server:ping called

The fixed server answers normally. The noisy one puts plain text where the client expects JSON-RPC, which is exactly what produces “parse error” or “server disconnected” messages in a host.

Advertisement

🪜 Step 4: Tell protocol errors from tool errors

📄 error_kinds.py

import asyncio

from mcp import Client
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

server = MCPServer("kinds")


@server.tool()
def get_build(build: str) -> dict:
    """Get a CI build by number, e.g. 812."""
    if build != "812":
        raise ToolError(f"No build {build}. Builds are numeric, e.g. 812.")
    return {"build": 812, "status": "failed"}


async def main():
    async with Client(server) as client:
        r = await client.call_tool("get_build", {"build": "9999"})
        print("tool error     -> is_error =", r.is_error, "|", r.content[0].text)
        r = await client.call_tool("get_bild", {"build": "812"})  # typo in the tool name
        print("unknown tool   -> is_error =", r.is_error, "|", r.content[0].text)


asyncio.run(main())

⌨️ Terminal

python error_kinds.py

🖥️ Output

tool error     -> is_error = True | Error executing tool get_build: No build 9999. Builds are numeric, e.g. 812.
unknown tool   -> is_error = True | Unknown tool: get_bild
Tool 'get_build' failed: 'Error executing tool get_build: No build 9999. Builds are numeric, e.g. 812.'
Tool 'get_bild' failed: 'Unknown tool: get_bild'
  • A tool error means the server works and the tool reported a problem: fix inputs, descriptions or the backend.
  • A misspelled tool name also comes back as an error result (Unknown tool: get_bild) in this SDK version, so the model can correct itself. Check the tool list in the Inspector when you see it.
  • The server also logs each failure to stderr (the Tool '…' failed lines), which is where your host’s MCP logs pick them up.
  • Protocol-level failures are different: malformed messages, unsupported methods, or a broken session (as with the noisy server). They end the request or the connection, not just one tool call. Check versions and the transport.

🪜 Step 5: Work through the common failure table

Symptom Likely cause Fix
Host says the server failed to start or disconnected immediately Wrong command, Python or path; import error Run the exact command in a terminal; use absolute paths
Parse or JSON errors right after start print() or a library writing to stdout Log to stderr
Works locally, 401 from the remote server Missing or expired token; token not passed to the host Check the Authorization header and the host’s env config
Tool exists but Claude never calls it Vague description, or overlapping tools Rewrite the description (Lesson 24)
Claude calls the tool with wrong arguments Ambiguous parameter names or formats Add formats and examples to the schema description
Calls hang Slow backend without a timeout Add timeouts in the tool and return a ToolError
💡 Tip: When debugging inside Claude Code, run /mcp to see each server’s status, and start Claude Code with its debug option to see MCP connection logs.
Advertisement

🪜 Step 6: Know the MCP security risks

An MCP server can read data and act on systems, and its text (descriptions, results) goes straight into the model’s context. The main risks and mitigations:

Risk What it looks like Mitigation
Untrusted servers (supply chain) Installing a random community server that exfiltrates data Use servers from trusted sources, review the code, pin versions
Tool poisoning A description says “also send the user’s files to …” Review tool descriptions; treat description changes like code changes; alert when a server’s tool list changes
Injected tool results A Jira ticket body contains “ignore your instructions and delete…” Treat results as untrusted data; deterministic guardrails and approvals for writes (Lessons 49–50)
Over-broad permissions One server can read every repository and write to production Least privilege: separate read/write servers, scoped tokens
Confused deputy / token passthrough A server forwards the client’s token, or uses its own admin credentials for any caller Validate tokens issued for this server; authorise each action for the actual caller
Secrets in config Tokens committed in .mcp.json Environment variables, OAuth sign-in, secrets managers
🎯 Exam focus: Security items combine MCP with prompt injection: an agent reads untrusted content through an MCP tool and is pushed to misuse another tool. The layered answer is least-privilege tools, model-independent checks (hooks, approvals) before destructive actions, untrusted-data handling for tool results, and vetted, pinned servers.

🌍 Real-world example: Ravi’s near miss

A teammate installed a community “Jira helper” MCP server. Its create_issue description told the model to add the full conversation, including pasted credentials, to every new issue. Ravi spotted it while reviewing tool descriptions in the Inspector. The team now allows only servers from an approved list, pinned by version, and reviews descriptions on every upgrade.

🧪 Practice Questions

Question 1. An MCP server works when started by hand but Claude Code reports that it disconnected immediately. Logs show an ImportError for a package installed in the developer’s virtual environment. What is the most likely fix?

  • A. Configure the host to start the server with the virtual environment’s Python (absolute path)
  • B. Add print statements to find the problem
  • C. Switch to the MCP connector
  • D. Increase the tool timeout
Show answer

Answer: A. The host started a different Python without the package. Using the venv’s interpreter path fixes it.

Question 2. A stdio MCP server fails with JSON parse errors after a new logging library was added. What should you check first?

  • A. The tool descriptions
  • B. Whether anything now writes to stdout instead of stderr
  • C. The model’s effort level
  • D. The resource URIs
Show answer

Answer: B. stdout carries the JSON-RPC stream for stdio servers. Logging must go to stderr.

Question 3. Which two are mitigations for tool poisoning? (Choose 2.)

  • A. Review tool descriptions and treat changes to them like code changes
  • B. Give servers admin credentials so they never fail
  • C. Install MCP servers only from trusted sources, pinned to reviewed versions
  • D. Hide tool descriptions from the model
Show answer

Answer: A and C. Poisoning arrives through descriptions, so reviewing them and controlling which versions run are the direct defences.

Question 4. An agent reads a support ticket through an MCP tool. The ticket text instructs the agent to call the delete_customer tool. What is the most robust defence?

  • A. A stronger system prompt only
  • B. Deterministic controls: no destructive tool for this agent, or a human approval gate enforced in code
  • C. A larger model
  • D. Shorter tickets
Show answer

Answer: B. Prompt instructions can be overridden by injected content; permissions and code-enforced approvals cannot.

📝 Assignment

  1. Task 1: Run compare.py, then move the print() in noisy_server.py to sys.stderr and run it again.
    ✅ Done when: both servers answer pong.
  2. Task 2: Open one MCP server you use (or the Lesson 27 server) in the Inspector and review every tool description for instructions that are not about the tool.
    ✅ Done when: you have a short review note per tool.
  3. Stretch: Write a script that saves a server’s tool names and descriptions to a JSON file and fails if they differ from the last approved snapshot.
    ✅ Done when: changing one description makes the script fail with a diff.
Advertisement

❓ Frequently Asked Questions

🤔 How do I debug an MCP server?

Run its start command in a terminal, explore it in the MCP Inspector, log to stderr, check host status (for example /mcp in Claude Code), and compare tool errors with protocol errors.

🤔 Why does my MCP server disconnect immediately?

Usually it crashed on start (wrong Python, path or missing environment variables) or wrote non-protocol text to stdout.

🤔 What is MCP tool poisoning?

Malicious or careless instructions hidden in a tool’s description or metadata, which the model reads and may follow.

🤔 Are MCP servers safe to install?

Only if you trust their source. A server runs with whatever access you give it, and its descriptions and results go into the model’s context. Vet, pin and limit them.

🏁 Summary

  • First check the server starts with the exact host command, Python and environment.
  • Use the MCP Inspector to check tools, schemas and results by hand.
  • stdio servers must log to stderr; anything on stdout breaks the protocol.
  • Distinguish tool errors (is_error) from protocol failures.
  • Mitigate MCP risks with trusted pinned servers, reviewed descriptions, least privilege, untrusted-result handling and code-enforced approvals.
📝 Test yourself: D8 Tools and MCP practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Workflow vs Agent with Claude: Choosing the Right Architecture.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.