Skip to main content
Glama
luchiniatwork

OpenAI WebSearch MCP Server

README.md
# OpenAI WebSearch MCP Server (TypeScript) πŸ”

[![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
[![Bun](https://img.shields.io/badge/Bun-1.2+-orange.svg)](https://bun.sh)
[![MCP Compatible](https://img.shields.io/badge/MCP-Compatible-green.svg)](https://modelcontextprotocol.io/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A TypeScript MCP server that provides intelligent web search capabilities using OpenAI's reasoning models and Web Search API. Built with Bun for blazing-fast performance.

> **What is MCP?** The [Model Context Protocol](https://modelcontextprotocol.io/) allows AI assistants like Claude to connect to external tools and data sources. This server adds web search capabilities to your AI assistant.

## Table of Contents

- [Features](#-features)
- [Quick Start](#-quick-start)
- [Configuration](#️-configuration)
- [Usage Examples](#-usage-examples)
- [Model Selection Guide](#-model-selection-guide)
- [Development](#-development)
- [Debugging](#-debugging)
- [Project Structure](#️-project-structure)

## ✨ Features

- **πŸ” OpenAI Web Search API**: Direct integration with OpenAI's Web Search API
- **🌍 Localized Results**: Support for location-based search customization
- **πŸ“ Rich Type Safety**: Full TypeScript types for all parameters and responses
- **πŸš€ Bun-Powered**: Lightning-fast runtime and package management
- **πŸ”§ Flexible Configuration**: Environment variable support for easy deployment
- **πŸ“š Source Citations**: Automatic extraction and formatting of web sources

## πŸš€ Quick Start

### Prerequisites

1. **[Bun](https://bun.sh)** runtime (v1.2 or higher)
   ```bash
   curl -fsSL https://bun.sh/install | bash
   ```

2. **OpenAI API Key** with Web Search API access
   - Get your API key from [OpenAI Platform](https://platform.openai.com/api-keys)
   - Ensure your account has access to the Web Search API

### Installation

```bash
# 1. Clone the repository
git clone https://github.com/yourusername/openai-websearch-mcp.git
cd openai-websearch-mcp

# 2. Install dependencies
bun install

# 3. Set up environment variables
cp .env.example .env

# 4. Edit .env and add your OpenAI API key
# OPENAI_API_KEY=sk-your-api-key-here
# OPENAI_DEFAULT_MODEL=gpt-5-mini
```

### Testing the Server

Before integrating with an MCP client, test that the server works:

```bash
# Run the server directly (it will wait for MCP protocol messages)
bun run start

# Or test with MCP Inspector (recommended)
bunx @modelcontextprotocol/inspector bun run src/index.ts
```

If the server starts successfully, you'll see:
```
openai-websearch-mcp v1.0.0 running on stdio
Default model: gpt-4o-search-preview
```

## βš™οΈ Configuration

### Environment Variables

The server requires the following environment variables:

| Variable               | Description          | Required | Default                 |
|------------------------|----------------------|----------|-------------------------|
| `OPENAI_API_KEY`       | Your OpenAI API key  | **Yes**  | -                       |
| `OPENAI_DEFAULT_MODEL` | Default model to use | No       | `gpt-4o-search-preview` |

Create a `.env` file in the project root:

```env
OPENAI_API_KEY=sk-your-api-key-here
OPENAI_DEFAULT_MODEL=gpt-4o-search-preview
```

### MCP Client Configuration

Configure your MCP client to connect to this server. Choose either the published package (recommended) or local development setup.

#### Claude Desktop

1. Find your config file location:
   - **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
   - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
   - **Linux**: `~/.config/Claude/claude_desktop_config.json`

2. Add this server configuration:

**Option 1: Using npx (recommended for published package)**

```json
{
  "mcpServers": {
    "openai-websearch-mcp": {
      "command": "npx",
      "args": ["-y", "openai-websearch-mcp"],
      "env": {
        "OPENAI_API_KEY": "sk-your-api-key-here",
        "OPENAI_DEFAULT_MODEL": "gpt-4o-search-preview"
      }
    }
  }
}
```

**Option 2: Using bunx (alternative for Bun users)**

```json
{
  "mcpServers": {
    "openai-websearch-mcp": {
      "command": "bunx",
      "args": ["openai-websearch-mcp"],
      "env": {
        "OPENAI_API_KEY": "sk-your-api-key-here",
        "OPENAI_DEFAULT_MODEL": "gpt-4o-search-preview"
      }
    }
  }
}
```

**Option 3: Local development setup**

```json
{
  "mcpServers": {
    "openai-websearch-mcp": {
      "command": "bun",
      "args": ["run", "/absolute/path/to/openai-websearch-mcp/src/index.ts"],
      "env": {
        "OPENAI_API_KEY": "sk-your-api-key-here",
        "OPENAI_DEFAULT_MODEL": "gpt-4o-search-preview"
      }
    }
  }
}
```

3. Restart Claude Desktop

4. Look for the πŸ”Œ icon in Claude to verify the server is connected

#### Cursor

1. Open Cursor Settings (`Cmd/Ctrl + ,`)
2. Search for "MCP" in settings
3. Add server configuration (same format as Claude Desktop above)
4. Restart Cursor

#### Other MCP Clients

Any MCP-compatible client can use this server with the stdio transport:

**Using npx:**
```bash
npx -y openai-websearch-mcp
```

**Using bunx:**
```bash
bunx openai-websearch-mcp
```

**Local development:**
```bash
bun run /absolute/path/to/openai-websearch-mcp/src/index.ts
```

## πŸ› οΈ Available Tools

### `openai_web_search`

Performs intelligent web search with AI reasoning capabilities.

#### Parameters

| Parameter       | Type     | Required | Description                                                                              | Default                 |
|-----------------|----------|----------|------------------------------------------------------------------------------------------|-------------------------|
| `input`         | `string` | **Yes**  | The search query or question                                                             | -                       |
| `model`         | `string` | No       | AI model to use                                                                          | `gpt-4o-search-preview` |
| `user_location` | `object` | No       | Location for localized results (must include `type: "approximate"` with country/city/region) | `null`                  |

#### Supported Models

All models support OpenAI's Web Search API:

- `gpt-4o-search-preview` - High-quality web search with comprehensive results (default)
- `gpt-4o-mini-search-preview` - Faster web search with efficient performance
- `gpt-5-search-api` - Advanced search capabilities

## πŸ’¬ Usage Examples

Once configured in your MCP client (Claude Desktop, Cursor, etc.), simply ask questions that require web search:

### Quick Search

```
"What are the latest developments in AI?"
```

The AI assistant will automatically use `openai_web_search` with the default model.

### Localized Search

```
"What tech meetups are happening in San Francisco this week?"
```

You can provide location context for more relevant local results.

### Specific Model Selection

```
"Use gpt-4o-mini-search-preview to search for: Python async best practices"
```

Choose a specific model for your search needs (speed vs quality trade-off).

### Common Use Cases

- πŸ“° **News & Current Events**: "What happened in tech news today?"
- πŸ“Š **Research**: "Latest papers on transformer architectures"
- πŸ—ΊοΈ **Local Information**: "Best coffee shops near me"
- πŸ’» **Technical Documentation**: "FastAPI async database patterns"
- 🎯 **Product Research**: "Compare M3 MacBook Pro vs Air"
- πŸ“ˆ **Market Data**: "Current AI startup funding trends"

## πŸ€– Model Selection Guide

### Standard Web Search (Default)

- **Recommended**: `gpt-4o-search-preview` (default)
- **Use Case**: General web search, current information, comprehensive results
- **Benefits**: High-quality responses with source citations

### Fast Web Search

- **Recommended**: `gpt-4o-mini-search-preview`
- **Use Case**: Quick queries, real-time information, faster responses
- **Benefits**: Lower latency, cost-effective for frequent searches

### Advanced Search

- **Recommended**: `gpt-5-search-api`
- **Use Case**: Complex search queries, advanced capabilities
- **Benefits**: Latest search features and capabilities

## πŸ“¦ Development

```bash
# Install dependencies
bun install

# Run in development mode with auto-reload
bun run dev

# Build for production
bun run build

# Run tests
bun test

# Type checking
bun run typecheck

# Lint code
bun run lint
```

## πŸ“€ Publishing to NPM

### Prerequisites

1. **NPM Account**: Create one at [npmjs.com/signup](https://www.npmjs.com/signup) if you don't have one
2. **Email Verified**: Ensure your NPM account email is verified

### Before Publishing

1. **Update package.json metadata**:
   - Replace `YOUR_USERNAME` in `repository.url` with your GitHub username
   - Replace `YOUR_USERNAME` in `homepage` with your GitHub username
   - Replace `YOUR_USERNAME` in `bugs.url` with your GitHub username
   - Optionally add `author` field: `"author": "Your Name <your.email@example.com>"`

2. **Remove any test dependencies**:
   - Check for any `file:` references in dependencies
   - Remove test tarballs from the project directory

### Publishing Steps

```bash
# 1. Login to NPM (one-time setup)
npm login
# Enter your username, password, and email when prompted

# 2. Verify you're logged in
npm whoami

# 3. Check what will be published (dry run)
npm publish --dry-run

# 4. Publish to NPM!
npm publish
```

### What Happens During Publish

The `prepublishOnly` script automatically runs:
1. `bun run typecheck` - Verifies TypeScript types
2. `bun run build` - Builds the dist/ folder
3. NPM packages and uploads only files in the `files` array (dist/, README.md, LICENSE)

### After Publishing

- Your package will be available at: `https://www.npmjs.com/package/openai-websearch-mcp`
- Users can install it with: `npx openai-websearch-mcp` or `bunx openai-websearch-mcp`
- It will appear in NPM search results

### Publishing Updates

When you need to publish a new version:

```bash
# Update version (choose one)
npm version patch  # Bug fixes: 1.0.0 -> 1.0.1
npm version minor  # New features: 1.0.0 -> 1.1.0
npm version major  # Breaking changes: 1.0.0 -> 2.0.0

# Publish the new version
npm publish
```

### Optional: Scoped Package

To publish under your username (e.g., `@yourusername/openai-websearch-mcp`):

1. Change `"name"` in package.json to `"@yourusername/openai-websearch-mcp"`
2. Publish with: `npm publish --access public`

### Verify Publication

After publishing, verify your package:

```bash
# Check package info
npm info openai-websearch-mcp

# Test installation
npx openai-websearch-mcp@latest
```

## πŸ—οΈ Project Structure

```
openai-websearch-mcp/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ index.ts              # MCP server entry point
β”‚   β”œβ”€β”€ types/
β”‚   β”‚   β”œβ”€β”€ openai.ts         # OpenAI API types
β”‚   β”‚   β”œβ”€β”€ mcp.ts            # MCP tool types
β”‚   β”‚   └── config.ts         # Configuration types
β”‚   β”œβ”€β”€ tools/
β”‚   β”‚   └── webSearch.ts      # Web search tool implementation
β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”œβ”€β”€ config.ts         # Environment config handler
β”‚   β”‚   β”œβ”€β”€ models.ts         # Model validation & defaults
β”‚   β”‚   └── errors.ts         # Error handling utilities
β”‚   └── constants.ts          # Model lists, defaults
β”œβ”€β”€ package.json
β”œβ”€β”€ tsconfig.json
└── README.md
```

## πŸ› Debugging & Troubleshooting

### Using MCP Inspector

The MCP Inspector provides a web UI for testing your server:

```bash
bunx @modelcontextprotocol/inspector bun run src/index.ts
```

This will open a browser interface where you can:
- See available tools
- Test tool calls with different parameters
- View request/response logs
- Debug errors

### Common Issues

#### "OPENAI_API_KEY environment variable is required"

**Solution**: Create a `.env` file with your API key:
```bash
echo "OPENAI_API_KEY=sk-your-key-here" > .env
```

#### "Invalid OpenAI API key format"

**Solution**: Ensure your API key starts with `sk-`

#### "Server not appearing in Claude Desktop"

**Solutions**:
1. Verify the absolute path in your config is correct
2. Restart Claude Desktop completely
3. Check Claude's logs:
   - macOS: `~/Library/Logs/Claude/`
   - Windows: `%APPDATA%\Claude\logs\`
   - Linux: `~/.config/Claude/logs/`

#### "Command 'bun' not found"

**Solution**: Install Bun:
```bash
curl -fsSL https://bun.sh/install | bash
```

### Logging

The server logs to stderr. To see detailed logs:

```bash
# Run with output visible
bun run src/index.ts 2>&1 | tee server.log
```

### Testing Individual Components

```bash
# Type checking
bun run typecheck

# Run specific tests (if implemented)
bun test

# Check if OpenAI API key works
# (Creates a simple test script to verify)
echo 'import OpenAI from "openai"; const client = new OpenAI(); console.log("API key valid");' | bun run -
```

## πŸ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## πŸ™ Acknowledgments

- πŸ”₯ Powered by [OpenAI's Web Search API](https://openai.com)
- πŸ› οΈ Built on the [Model Context Protocol](https://modelcontextprotocol.io/)
- ⚑ Runtime by [Bun](https://bun.sh)
- 🐍 Inspired by [ConechoAI's Python implementation](https://github.com/ConechoAI/openai-websearch-mcp)