Skip to main content
Glama

Web Search

search
Idempotent

Search the web and receive a synthesized answer with source URLs for current information, documentation lookups, and research questions.

Instructions

Web search via Claude Code CLI using WebSearch and WebFetch tools. Searches the web and synthesizes a comprehensive answer with source URLs.

Use for: current information, documentation lookups, API references, comparing libraries, and research questions.

Cost: Typically ~$0.02-0.05/search with Sonnet.

Tips:

  • Ask specific, focused questions for best results.

  • Results include source URLs for verification.

  • Use maxResponseLength to control response verbosity.

  • Increase timeout for complex research queries that may require multiple web fetches.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query or question
modelNoModel alias or full Claude model name
sessionIdNoClaude session ID to resume with --resume
noSessionPersistenceNoDisable session persistence for ephemeral print calls
workingDirectoryNoWorking directory for the CLI
timeoutNoTimeout in milliseconds
maxResponseLengthNoSoft limit on response length in words
maxBudgetUsdNoMaximum cost budget in USD for this call (passed to --max-budget-usd)
effortNoEffort level: low, medium, high, or max (default: medium for search)

Implementation Reference

  • The core handler function that executes the search tool logic. Resolves model, loads prompt, builds Claude CLI args with WebSearch/WebFetch tools, spawns Claude process, and parses the output.
    export async function executeSearch(input: SearchInput): Promise<SearchResult> {
      const { query, maxResponseLength, sessionId, noSessionPersistence, maxBudgetUsd, effort } = input;
      const model = resolveModel("search", input.model);
      const timeout = clampTimeout(input.timeout, SEARCH_TIMEOUT);
    
      const cwd = await resolveCwd(input.workingDirectory);
    
      const prompt = loadPrompt("search.md", {
        QUERY: query,
        LENGTH_LIMIT: buildLengthLimit(maxResponseLength) || "Provide a focused synthesis. Aim for 500-1500 words unless the topic clearly warrants less.",
      });
    
      const args = buildClaudeArgs({
        model,
        fallbackModel: getFallbackModel(),
        maxBudgetUsd: resolveMaxBudget(maxBudgetUsd),
        effort: resolveEffort("search", effort),
        sessionId,
        noSessionPersistence,
        allowedTools: ["WebSearch", "WebFetch"],
      });
    
      const result = await spawnClaude({ args, cwd, stdin: prompt, timeout });
    
      if (result.timedOut) {
        return {
          response: tryParsePartial(result.stdout, result.stderr, timeout),
          model,
          timedOut: true,
          resolvedCwd: cwd,
        };
      }
    
      const parsed = parseClaudeOutput(result.stdout, result.stderr);
      checkAndThrow(result, parsed);
    
      return {
        response: parsed.response,
        model,
        sessionId: parsed.sessionId,
        totalCostUsd: parsed.totalCostUsd,
        usage: parsed.usage,
        timedOut: false,
        resolvedCwd: cwd,
      };
    }
  • Input schema/interface for the search tool.
    export interface SearchInput {
      query: string;
      model?: string;
      sessionId?: string;
      noSessionPersistence?: boolean;
      workingDirectory?: string;
      timeout?: number;
      maxResponseLength?: number;
      maxBudgetUsd?: number;
      effort?: string;
    }
  • Output/result interface for the search tool.
    export interface SearchResult {
      response: string;
      model?: string;
      sessionId?: string;
      totalCostUsd?: number;
      usage?: ClaudeUsage;
      timedOut: boolean;
      resolvedCwd: string;
    }
  • src/index.ts:234-292 (registration)
    Registers the 'search' tool on the MCP server with its name, schema, annotations, and handler callback that delegates to executeSearch.
    server.registerTool(
      "search",
      {
        title: "Web Search",
        description: searchDescription,
        inputSchema: {
          query: z.string().describe("Search query or question"),
          model: z.string().optional().describe("Model alias or full Claude model name"),
          sessionId: z.string().optional().describe("Claude session ID to resume with --resume"),
          noSessionPersistence: z.boolean().optional().describe("Disable session persistence for ephemeral print calls"),
          workingDirectory: z.string().optional().describe("Working directory for the CLI"),
          timeout: z.number().optional().describe("Timeout in milliseconds"),
          maxResponseLength: z.number().int().positive().optional().describe("Soft limit on response length in words"),
          maxBudgetUsd: z.number().positive().optional().describe("Maximum cost budget in USD for this call (passed to --max-budget-usd)"),
          effort: z.string().optional().describe("Effort level: low, medium, high, or max (default: medium for search)"),
        },
        annotations: searchAnnotations,
      },
      async (input, extra) => {
        const start = Date.now();
        const heartbeat = maybeStartHeartbeat(
          extra._meta as { progressToken?: string | number } | undefined,
          extra.sendNotification as ProgressNotificationSender,
        );
        try {
          const result = await executeSearch(input);
    
          const sessionId = result.sessionId ?? input.sessionId;
          if (sessionId) {
            persist(sessionStore, sessionId, result);
          }
    
          const text = result.timedOut
            ? `${result.response}\n\n---\n(timed out)`
            : result.response;
    
          return {
            content: [{ type: "text" as const, text }],
            _meta: buildMeta({
              durationMs: Date.now() - start,
              model: result.model,
              sessionId: result.sessionId,
              totalCostUsd: result.totalCostUsd,
              usage: result.usage,
              timedOut: result.timedOut,
            }),
          };
        } catch (e) {
          console.error("[search]", e);
          return {
            content: [{ type: "text" as const, text: `Error: ${getErrorMessage(e)}` }],
            isError: true,
            _meta: buildMeta({ durationMs: Date.now() - start }),
          };
        } finally {
          heartbeat.stop();
        }
      },
    );
  • Rich description string for the search tool, used during registration.
    export const searchDescription = `Web search via Claude Code CLI using WebSearch and WebFetch tools. Searches the web and synthesizes a comprehensive answer with source URLs.
    
    Use for: current information, documentation lookups, API references, comparing libraries, and research questions.
    
    Cost: Typically ~$0.02-0.05/search with Sonnet.
    
    Tips:
    - Ask specific, focused questions for best results.
    - Results include source URLs for verification.
    - Use maxResponseLength to control response verbosity.
    - Increase timeout for complex research queries that may require multiple web fetches.`;
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already include idempotentHint=true, openWorldHint=true, destructiveHint=false. Description adds valuable context: cost estimate ($0.02-0.05), synthesis behavior, and control parameters (timeout, maxResponseLength). No contradictions.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Six sentences plus bullet points. Every sentence adds value: purpose, use cases, cost, tips. Efficiently structured, though could be slightly more organized. Not wordy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the open-world, cost-incurring nature with 9 parameters and no output schema, the description covers purpose, cost, usage guidance, and key controls. Return format is implied (answer with URLs). Lacks explicit mention of network dependency or authentication, but sufficient for typical use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

All 9 parameters have schema descriptions (100% coverage). Description mentions some parameters (maxResponseLength, timeout) but does not add additional semantic meaning beyond what the schema provides. Baseline 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly states verb 'search' and resource 'web', and that it synthesizes a comprehensive answer with source URLs. However, sibling tool 'query' could be ambiguous; no explicit differentiation from 'query' is provided.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly lists use cases (current info, documentation lookups, API references, etc.) and provides practical tips. Does not explicitly state when not to use or alternatives, but the context is clear enough.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/hampsterx/claude-mcp-bridge'

If you have feedback or need assistance with the MCP directory API, please join our Discord server