Skip to main content
Glama
altinakseven

Tavily MCP Server

by altinakseven

web_search

Search the web to find relevant information with content snippets and direct answers. Configure search depth, result counts, and domain filtering for precise results.

Instructions

Search the web using Tavily API. Returns relevant search results with content snippets.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesThe search query to execute
search_depthNoThe depth of the search (basic or advanced)basic
include_answerNoWhether to include a direct answer to the query
max_resultsNoMaximum number of search results to return
include_domainsNoList of domains to include in search
exclude_domainsNoList of domains to exclude from search

Implementation Reference

  • The handleWebSearch method executes the web search tool logic. It validates input arguments, makes an API call to Tavily search service, formats the response into readable markdown, and returns the results as MCP content.
    public async handleWebSearch(args: any) {
      try {
        const searchRequest: TavilySearchRequest = {
          query: args.query,
          search_depth: args.search_depth || "basic",
          include_answer: args.include_answer !== false,
          include_raw_content: false,
          max_results: args.max_results || 5,
          include_domains: args.include_domains,
          exclude_domains: args.exclude_domains,
        };
    
        const response = await axios.post<TavilyResponse>(
          "https://api.tavily.com/search",
          searchRequest,
          {
            headers: {
              "Content-Type": "application/json",
              "Authorization": `Bearer ${this.apiKey}`,
            },
          }
        );
    
        const data = response.data;
        
        // Format the response for better readability
        let formattedResponse = `# Search Results for: "${data.query}"\n\n`;
        
        if (data.answer) {
          formattedResponse += `## Direct Answer\n${data.answer}\n\n`;
        }
        
        formattedResponse += `## Search Results\n\n`;
        
        data.results.forEach((result, index) => {
          formattedResponse += `### ${index + 1}. ${result.title}\n`;
          formattedResponse += `**URL:** ${result.url}\n`;
          if (result.published_date) {
            formattedResponse += `**Published:** ${result.published_date}\n`;
          }
          formattedResponse += `**Score:** ${result.score}\n\n`;
          formattedResponse += `${result.content}\n\n`;
          formattedResponse += `---\n\n`;
        });
    
        if (data.follow_up_questions && data.follow_up_questions.length > 0) {
          formattedResponse += `## Follow-up Questions\n`;
          data.follow_up_questions.forEach((question, index) => {
            formattedResponse += `${index + 1}. ${question}\n`;
          });
        }
    
        return {
          content: [
            {
              type: "text",
              text: formattedResponse,
            },
          ],
        };
      } catch (error) {
        if (axios.isAxiosError(error)) {
          const errorMessage = error.response?.data?.error || error.message;
          throw new Error(`Tavily API error: ${errorMessage}`);
        }
        throw new Error(`Search failed: ${error}`);
      }
    }
  • TypeScript interfaces defining the structure for TavilySearchRequest, TavilySearchResult, and TavilyResponse. These provide type safety and validation for the API request and response data.
    interface TavilySearchRequest {
      query: string;
      search_depth?: "basic" | "advanced";
      include_answer?: boolean;
      include_raw_content?: boolean;
      max_results?: number;
      include_domains?: string[];
      exclude_domains?: string[];
    }
    
    interface TavilySearchResult {
      title: string;
      url: string;
      content: string;
      score: number;
      published_date?: string;
    }
    
    interface TavilyResponse {
      answer?: string;
      query: string;
      response_time: number;
      images?: string[];
      follow_up_questions?: string[];
      results: TavilySearchResult[];
    }
  • src/index.ts:64-111 (registration)
    Registers the web_search tool with the MCP server using ListToolsRequestSchema. Defines the tool name, description, and complete inputSchema with parameters like query, search_depth, max_results, and domain filters.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: "web_search",
            description: "Search the web using Tavily API. Returns relevant search results with content snippets.",
            inputSchema: {
              type: "object",
              properties: {
                query: {
                  type: "string",
                  description: "The search query to execute",
                },
                search_depth: {
                  type: "string",
                  enum: ["basic", "advanced"],
                  description: "The depth of the search (basic or advanced)",
                  default: "basic",
                },
                include_answer: {
                  type: "boolean",
                  description: "Whether to include a direct answer to the query",
                  default: true,
                },
                max_results: {
                  type: "number",
                  description: "Maximum number of search results to return",
                  default: 5,
                  minimum: 1,
                  maximum: 20,
                },
                include_domains: {
                  type: "array",
                  items: { type: "string" },
                  description: "List of domains to include in search",
                },
                exclude_domains: {
                  type: "array",
                  items: { type: "string" },
                  description: "List of domains to exclude from search",
                },
              },
              required: ["query"],
            },
          },
        ],
      };
    });
  • src/index.ts:113-118 (registration)
    Routes tool execution requests to the appropriate handler. When a CallToolRequestSchema request comes in for 'web_search', it invokes the handleWebSearch method.
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      if (request.params.name === "web_search") {
        return await this.handleWebSearch(request.params.arguments);
      }
      throw new Error(`Unknown tool: ${request.params.name}`);
    });
  • JSON Schema definition for the web_search tool input parameters. Specifies required fields (query), optional fields with defaults (search_depth, include_answer, max_results), and array fields for domain filtering.
    inputSchema: {
      type: "object",
      properties: {
        query: {
          type: "string",
          description: "The search query to execute",
        },
        search_depth: {
          type: "string",
          enum: ["basic", "advanced"],
          description: "The depth of the search (basic or advanced)",
          default: "basic",
        },
        include_answer: {
          type: "boolean",
          description: "Whether to include a direct answer to the query",
          default: true,
        },
        max_results: {
          type: "number",
          description: "Maximum number of search results to return",
          default: 5,
          minimum: 1,
          maximum: 20,
        },
        include_domains: {
          type: "array",
          items: { type: "string" },
          description: "List of domains to include in search",
        },
        exclude_domains: {
          type: "array",
          items: { type: "string" },
          description: "List of domains to exclude from search",
        },
      },
      required: ["query"],
    },
Behavior2/5

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

With no annotations provided, the description carries full burden but offers minimal behavioral insight. It mentions the API provider (Tavily) and output format (results with snippets), but lacks details on rate limits, authentication needs, error handling, or performance characteristics that would help the agent anticipate behavior.

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

Conciseness5/5

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

The description is a single, efficient sentence that front-loads the core purpose and key output details. Every word contributes essential information with zero waste, making it optimally concise.

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

Completeness3/5

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

For a 6-parameter tool with no annotations and no output schema, the description is adequate but minimal. It covers the basic purpose and output format, but lacks depth on behavioral traits, usage context, or richer operational details that would enhance agent understanding.

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?

Schema description coverage is 100%, so the schema fully documents all 6 parameters. The description adds no parameter-specific information beyond what's in the schema, meeting the baseline for high coverage without additional value.

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?

The description clearly states the action ('Search the web') and resource ('using Tavily API'), specifying it returns 'relevant search results with content snippets'. It's specific about the API provider and output format, though without sibling tools, differentiation isn't applicable.

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

Usage Guidelines2/5

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

No guidance is provided on when to use this tool versus alternatives. The description doesn't mention any prerequisites, constraints, or typical use cases, leaving the agent with no contextual direction for tool selection.

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/altinakseven/tavily-mcp-server'

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