惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

A
About on SuperTechFans
C
Cybersecurity and Infrastructure Security Agency CISA
N
News and Events Feed by Topic
C
Cisco Blogs
Cisco Talos Blog
Cisco Talos Blog
A
Arctic Wolf
Scott Helme
Scott Helme
P
Palo Alto Networks Blog
S
Schneier on Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Tor Project blog
量子位
G
Google Developers Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
B
Blog RSS Feed
NISL@THU
NISL@THU
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
AWS News Blog
AWS News Blog
爱范儿
爱范儿
Last Week in AI
Last Week in AI
Y
Y Combinator Blog
L
LINUX DO - 最新话题
Security Archives - TechRepublic
Security Archives - TechRepublic
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
Secure Thoughts
Cloudbric
Cloudbric
aimingoo的专栏
aimingoo的专栏
L
Lohrmann on Cybersecurity
TaoSecurity Blog
TaoSecurity Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Hacker News: Ask HN
Hacker News: Ask HN
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The GitHub Blog
The GitHub Blog
有赞技术团队
有赞技术团队
S
Security @ Cisco Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cyber Attacks, Cyber Crime and Cyber Security
G
GRAHAM CLULEY
P
Proofpoint News Feed
V
V2EX
Martin Fowler
Martin Fowler
C
CERT Recently Published Vulnerability Notes
Attack and Defense Labs
Attack and Defense Labs
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Cloudflare Blog
SecWiki News
SecWiki News
罗磊的独立博客
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
小众软件
小众软件
The Last Watchdog
The Last Watchdog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
MCP Discovery: Why Your MCP Server Needs Better Tool Discovery Than You Think (After 85 Production Outages)
KevinTen · 2026-06-25 · via DEV Community

MCP Discovery: Why Your MCP Server Needs Better Tool Discovery Than You Think (After 85 Production Outages)

Honestly, I didn't think tool discovery would be a problem.

I've built 10+ MCP servers now, 1,800 hours into my knowledge base project, and after 85 production outages, I can tell you this: bad tool discovery will kill your MCP server before bad code ever does.

Let me explain.

The Problem That Nobody Talks About

MCP is pretty straightforward, right? You implement tools/list and tools/call, and you're done. The AI figures it out, the user is happy.

Except that's not what actually happens.

I've spent three days debugging this one issue: my AI client knew I had a "search knowledge base" tool, but it kept calling the wrong tool name. It kept calling search_knowledgebase instead of search_papers. I added aliases. I improved descriptions. Nothing worked.

Then I realized the real problem: the LLM hallucinates tool names. It doesn't read your tool list—it guesses based on what it thinks the name should be. And when it guesses wrong, your server gets a tool not found error, the AI panics, and the entire conversation dies.

I learned this the hard way. Three separate production outages, all because of bad discovery. Today I want to share what I fixed, the code I wrote, and how you can avoid the same pain.

What Actually Goes Wrong With MCP Discovery

Let me count the ways I've messed this up:

1. The LLM Hallucinates Tool Names

This is the big one. My tool is called search_papers. The LLM thinks "search papers" → search_paper (singular). Or search_knowledge → wrong again. Or find_paper → nope.

Every time it happens, you get:

Error: Tool not found: search_paper
Available tools: search_papers, get_paper, ...

Then the LLM tries again, gets it wrong again, and eventually gives up. User experience: zero stars.

2. Descriptions That Don't Help

When I started, my tool descriptions were:

"description": "Searches papers"

That's useless. The LLM doesn't know when to use it. It doesn't know what kind of search it is. It doesn't know what returns. I've had my AI client use my "search" tool when it should have used "get paper by id" because the description was bad.

3. Parameter Discovery Problems

It's not just tool names—it's parameter names too. My parameter is called query, but the LLM keeps passing question or search_term. Same problem: error, retry, failure.

4. No Graceful Degradation

When I first started, if the tool name was wrong, I just returned an error. That's the spec, right? Well, the spec doesn't say you can't help the LLM find the right tool.

My Solution: Fuzzy Discovery That Actually Works

After three outages, I built a fuzzy discovery layer into my MCP server. Here's what it looks like in Java Spring Boot:

@Component
public class McpDiscoveryFilter implements OncePerRequestFilter {

    private final List<ToolDefinition> tools;
    private final FuzzyMatcher fuzzyMatcher;

    public McpDiscoveryFilter(List<ToolDefinition> tools) {
        this.tools = tools;
        this.fuzzyMatcher = new FuzzyMatcher();
    }

    @Override
    protected void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain filterChain
    ) throws ServletException, IOException {

        // Only intercept tools/call
        if (!request.getRequestURI().equals("/mcp/tools/call")) {
            filterChain.doFilter(request, response);
            return;
        }

        // Read the body
        var body = request.getReader().lines().collect(Collectors.joining());
        var callRequest = objectMapper.readValue(body, CallToolRequest.class);

        String requestedName = callRequest.getName();
        Optional<ToolDefinition> exactMatch = findExactMatch(requestedName);

        if (exactMatch.isPresent()) {
            // Exact match found, proceed normally
            proceedWithRequest(request, response, filterChain, body, exactMatch.get());
            return;
        }

        // No exact match — try fuzzy match
        List<MatchResult> matches = fuzzyMatcher.findBestMatches(requestedName, tools);

        if (matches.isEmpty() || matches.get(0).getScore() < 0.7) {
            // Still no good — return helpful error
            writeHelpfulError(response, requestedName, matches);
            return;
        }

        // We found a close match — rewrite the request and proceed!
        ToolDefinition bestMatch = matches.get(0).getTool();
        logger.info("Fuzzy matched: {} -> {} (score: {})", 
            requestedName, bestMatch.getName(), matches.get(0).getScore());

        // Rewrite with correct name and proceed
        callRequest.setName(bestMatch.getName());
        String rewrittenBody = objectMapper.writeValueAsString(callRequest);
        proceedWithRewrittenBody(request, response, filterChain, rewrittenBody, bestMatch);
    }

    private Optional<ToolDefinition> findExactMatch(String name) {
        return tools.stream()
            .filter(t -> t.getName().equals(name))
            .findFirst();
    }

    private void writeHelpfulError(
        HttpServletResponse response,
        String requestedName,
        List<MatchResult> matches
    ) throws IOException {
        Map<String, Object> error = new HashMap<>();
        error.put("result", null);
        error.put("error", Map.of(
            "message", String.format("Tool '%s' not found. Did you mean one of these? %s",
                requestedName,
                matches.stream()
                    .limit(3)
                    .map(m -> m.getTool().getName())
                    .collect(Collectors.joining(", "))
            ),
            "code", "TOOL_NOT_FOUND"
        ));
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json");
        objectMapper.writeValue(response.getWriter(), error);
    }
}

And the fuzzy matching implementation is simple—I use the Levenshtein distance algorithm:

public class FuzzyMatcher {

    public List<MatchResult> findBestMatches(String input, List<ToolDefinition> tools) {
        return tools.stream()
            .map(tool -> {
                int distance = levenshteinDistance(input.toLowerCase(), tool.getName().toLowerCase());
                double score = 1.0 - (double) distance / Math.max(input.length(), tool.getName().length());
                return new MatchResult(tool, score);
            })
            .filter(mr -> mr.getScore() > 0.5)
            .sorted((a, b) -> Double.compare(b.getScore(), a.getScore()))
            .collect(Collectors.toList());
    }

    private int levenshteinDistance(String s1, String s2) {
        int[][] dp = new int[s1.length() + 1][s2.length() + 1];

        for (int i = 0; i <= s1.length(); i++) {
            dp[i][0] = i;
        }
        for (int j = 0; j <= s2.length(); j++) {
            dp[0][j] = j;
        }

        for (int i = 1; i <= s1.length(); i++) {
            for (int j = 1; j <= s2.length(); j++) {
                int cost = (s1.charAt(i - 1) == s2.charAt(j - 1)) ? 0 : 1;
                dp[i][j] = Math.min(
                    Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1),
                    dp[i - 1][j - 1] + cost
                );
            }
        }

        return dp[s1.length()][s2.length()];
    }
}

public record MatchResult(ToolDefinition tool, double score) {}

The Results: 83% Fewer Tool Not Found Errors

After deploying this, I checked my logs. Here's what happened:

  • Before: 12-15 tool not found errors per day
  • After: 2-3 per day
  • Reduction: 83%

That's massive. Most of the hallucinated tool names are close, just pluralization wrong or slight spelling variation. The fuzzy matching just fixes them automatically—user never even knows.

When it can't fix it automatically, it gives the LLM suggestions: "Did you mean one of these?" That's way better than just "tool not found"—the LLM can correct itself instead of giving up.

Second Improvement: Better Tool Descriptions That Actually Guide the LLM

I used to write tool descriptions like this:

{
  "name": "search_papers",
  "description": "Searches papers"
}

Useless. Now I write:

{
  "name": "search_papers",
  "description": "Search my personal knowledge base for papers and notes by semantic similarity. Use this when you need to find information I've previously saved that's relevant to the current conversation. Returns the most relevant papers with their content. Parameters: query (string) - the search query based on the current context."
}

That's 5x longer, but it tells the LLM:

  1. What it does: semantic similarity search on personal knowledge base
  2. When to use it: when you need previously saved info relevant to current context
  3. What it returns: relevant papers with content
  4. What the parameter means: clear description of query

Since I improved descriptions, I've seen about 30% fewer cases where the AI chooses the wrong tool intentionally. It just knows better now.

Third Improvement: Parameter Aliases Too

It's not just tool names—parameters get hallucinated too. I added parameter aliasing:

public class ParameterAliasResolver {
    private final Map<String, String> aliases = new HashMap<>();

    public ParameterAliasResolver() {
        // Common aliases for common parameter names
        aliases.put("question", "query");
        aliases.put("search", "query");  
        aliases.put("search_term", "query");
        aliases.put("id", "paper_id");
        aliases.put("paperId", "paper_id");
        aliases.put("key", "api_key");
        aliases.put("token", "api_key");
    }

    public void addAlias(String alias, String correctName) {
        aliases.put(alias.toLowerCase(), correctName);
    }

    public String resolve(String paramName) {
        return aliases.getOrDefault(paramName.toLowerCase(), paramName);
    }

    public void resolveAll(Map<String, Object> params) {
        List<String> keysToRemove = new ArrayList<>();
        Map<String, Object> toAdd = new HashMap<>();

        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String resolved = resolve(entry.getKey());
            if (!resolved.equals(entry.getKey())) {
                keysToRemove.add(entry.getKey());
                toAdd.put(resolved, entry.getValue());
            }
        }

        keysToRemove.forEach(params::remove);
        params.putAll(toAdd);
    }
}

Then in your tool call handler:

public CallToolResult callTool(String name, Map<String, Object> args) {
    parameterAliasResolver.resolveAll(args);
    // proceed with correct parameter names
}

This fixes another 10-15% of errors. Common parameter name variations just work automatically.

Fourth Improvement: Tools Registry With Metadata

I ended up building a proper tools registry that holds all the metadata in one place:

@Configuration
public class ToolRegistryConfiguration {

    @Bean
    public ToolRegistry toolRegistry(List<McpTool> tools) {
        ToolRegistry registry = new ToolRegistry();
        tools.forEach(registry::register);
        return registry;
    }
}

public interface McpTool {
    ToolDefinition getDefinition();
    Object call(Map<String, Object> args) throws ToolException;
}

public class ToolRegistry {
    private final Map<String, McpTool> tools = new HashMap<>();
    private final ParameterAliasResolver aliasResolver = new ParameterAliasResolver();

    public void register(McpTool tool) {
        ToolDefinition def = tool.getDefinition();
        tools.put(def.getName(), tool);

        // Register aliases from the definition if provided
        if (def.getAliases() != null) {
            for (String alias : def.getAliases()) {
                aliasResolver.addAlias(alias, def.getName());
            }
        }
    }

    // ... fuzzy matching logic here
}

This keeps everything organized. Each tool just implements the interface, gets automatically registered, and discovery just works.

Pros and Cons: Should You Add This To Your MCP Server?

Let's be honest—this adds complexity. Is it worth it?

Pros ✅

  1. Massively better user experience: Most errors just disappear automatically. Users don't need to know why—it just works.
  2. Helps with different client patterns: Different MCP clients have different patterns of generating tool names. This handles all of them.
  3. Very little runtime overhead: Fuzzy matching against 20-30 tools is negligible—takes less than 1ms.
  4. Backward compatible: Doesn't change the protocol, just adds graceful degradation.
  5. Easy to implement: The entire fuzzy matcher is ~50 lines of code.

Cons ❌

  1. Adds code complexity: You need an extra filter/layer. Not a big deal, but it's extra code.
  2. Could potentially match wrong tool: If two tools have very similar names, it might guess wrong. But in practice, this is rare—with the 0.7 threshold, it only matches when it's confident.
  3. Violates "strict" interpretation of the spec: The spec says "return error if tool not found". But the spec doesn't prohibit helping the LLM correct itself. I think this is a reasonable extension that improves the ecosystem.

Who Should Do This?

  • Any production MCP server: Definitely do this. Your users will thank you.
  • Personal/side project: Still do it—you'll thank yourself when you don't have to debug why the AI keeps calling the wrong tool.
  • One-off toy example: Maybe skip it if it's just a demo. But even then, why not?

What I Learned After 85 Outages

Here's the thing—MCP is a new protocol. Everybody's figuring it out as we go. The spec covers the basics, but it doesn't cover all the edge cases that happen in production.

I used to think: "The LLM should know better. It should read the tool list correctly."

But that's not how LLMs work. They predict the next token—they don't "read" like humans. They guess based on patterns. And "search paper" → search_paper is a totally reasonable guess from their perspective.

Instead of fighting the LLM, work with it. Add a little fuzzy discovery, and most of your problems just go away.

Another thing I learned: graceful degradation is everything. It's better to fix the mistake automatically than to fail and make the user fix it. The user didn't do anything wrong—the LLM hallucinated. Why should the user pay the price?

Real Numbers From My Production

Let me leave you with the actual numbers from my server after two weeks:

Metric Before Fuzzy Discovery After Fuzzy Discovery
Tool Not Found Errors/day 14 2
Successful Tool Calls/day 287 301
Success Rate 95.1% 99.3%
User Complaints about "it doesn't work" 2-3/week 0

That's the difference between "this is flaky" and "this just works".

Your Turn

Have you built an MCP server? Have you noticed the LLM hallucinating tool names or parameter names? I'd love to hear—am I the only one who's run into this? Do you have a different solution?

Drop a comment below and let me know what your experience has been with MCP discovery. What other hidden production gotchas have you found?