npm package: @soramash/slack-mcp-server-typescript
Description: A Model Context Protocol server for Slack integration written in TypeScript
Author: soramash
Latest version: 0.3.0

# Slack MCP Server (TypeScript)

A Model Context Protocol (MCP) server that enables AI assistants to interact with Slack workspaces. This TypeScript implementation provides tools for reading messages, posting messages, managing channels, and more through the Slack API.

## Features

- **Channel Management**: List channels, get channel info, create channels
- **Message Operations**: Send messages, read message history, reply to threads
- **User Management**: Get user information, list workspace members
- **File Operations**: Upload files, share files in channels
- **Search**: Search messages and files across the workspace
- **🆕 AI-Powered Search**: Advanced search with keyword expansion (Japanese/English)
- **Reactions**: Add and remove emoji reactions to messages

## New AI Search Features 🚀

We've significantly enhanced the AI search functionality with two powerful tools:

### 🔍 `ai_search_messages` - Basic AI-Powered Search
- Expands search terms with related keywords in both Japanese and English
- Searches multiple variations of your query
- Combines and deduplicates results from all searches
- Filters results to public channels only

### ✨ `enhanced_ai_search_messages` - Advanced AI Search with Analytics
Our new flagship search tool provides comprehensive analysis:

**Key Features:**
- **AI-Powered Keyword Expansion**: Generates contextually relevant related terms
- **Multi-Language Support**: Seamlessly handles Japanese and English queries
- **Comprehensive Analysis**: 
  - Temporal distribution (24h, 1week, 1month, older)
  - Channel activity analysis
  - User participation metrics
  - Keyword effectiveness scoring
- **Confidence Scoring**: AI-calculated confidence score (0-100%) based on search quality
- **AI-Generated Summaries**: Intelligent summaries of search results with key insights
- **Actionable Recommendations**: Specific next steps and suggested actions
- **Public Channel Safety**: Automatically filters out private channels and sensitive content

**Usage Examples:**

Basic search:
```json
{
  "tool": "enhanced_ai_search_messages",
  "arguments": {
    "query": "インシデント"
  }
}
```

Advanced search with full analysis:
```json
{
  "tool": "enhanced_ai_search_messages", 
  "arguments": {
    "query": "API エラー",
    "count": 20,
    "sort": "timestamp",
    "include_analysis": true,
    "detailed_summary": true
  }
}
```

See [ENHANCED_AI_SEARCH_GUIDE.md](./ENHANCED_AI_SEARCH_GUIDE.md) for comprehensive documentation.

## Prerequisites

- Node.js 18.0 or higher
- A Slack workspace with admin permissions
- Slack Bot Token with appropriate scopes
- **For Search Features**: Slack User Token with `search:read` scope

## Installation

1. Clone this repository:
```bash
git clone https://github.com/soramash/mcp-slack-typescript.git
cd mcp-slack-typescript
```

2. Install dependencies:
```bash
npm install
```

3. Set up your Slack Bot Token (see Configuration section below)

## Configuration

### Setting up Slack Bot Token

1. Go to [Slack API](https://api.slack.com/apps) and create a new app
2. Navigate to "OAuth & Permissions" in the sidebar
3. Add the following Bot Token Scopes:
   - `channels:read` - View basic information about public channels
   - `channels:write` - Manage public channels
   - `chat:write` - Send messages as the bot
   - `chat:write.public` - Send messages to channels the bot isn't a member of
   - `files:read` - View files shared in channels and conversations
   - `files:write` - Upload, edit, and delete files
   - `groups:read` - View basic information about private channels
   - `im:read` - View basic information about direct messages
   - `mpim:read` - View basic information about group direct messages
   - `reactions:read` - View emoji reactions and their associated content
   - `reactions:write` - Add and edit emoji reactions
   - `users:read` - View people in the workspace
   - `channels:history` - View messages and other content in public channels
   - `groups:history` - View messages and other content in private channels
   - `im:history` - View messages and other content in direct messages
   - `mpim:history` - View messages and other content in group direct messages

4. Install the app to your workspace
5. Copy the "Bot User OAuth Token" (starts with `xoxb-`)

### Setting up User Token for Search (Optional)

The search functionality requires a User OAuth Token because Slack's search API is not available with Bot tokens.

1. In your Slack app settings, navigate to "OAuth & Permissions"
2. Under "User Token Scopes", add:
   - `search:read` - Search messages and files
3. Install/reinstall the app to your workspace
4. Copy the "User OAuth Token" (starts with `xoxp-`)

**Note:** Without a user token, the search_messages functionality will be disabled, but all other features will work normally.

### Environment Variables

Set your Slack Bot Token as an environment variable:

```bash
export SLACK_BOT_TOKEN="xoxb-your-bot-token-here"
export SLACK_USER_TOKEN="xoxp-your-user-token-here"  # Optional, for search functionality
```

Or create a `.env` file in the project root:
```
SLACK_BOT_TOKEN=xoxb-your-bot-token-here
SLACK_USER_TOKEN=xoxp-your-user-token-here
```

## Usage

### Development

```bash
npm run dev
```

### Build and Run

```bash
npm run build
npm start
```

### Using with Claude Desktop

Add the following configuration to your Claude Desktop config file:

#### Basic Configuration (with AI search enabled)

```json
{
  "mcpServers": {
    "slack-typescript": {
      "command": "node",
      "args": ["path/to/your/project/dist/index.js"],
      "env": {
        "SLACK_BOT_TOKEN": "xoxb-your-bot-token-here",
        "SLACK_USER_TOKEN": "xoxp-your-user-token-here",
        "AI_PROVIDER": "openai",
        "OPENAI_API_KEY": "sk-your-openai-api-key-here"
      }
    }
  }
}
```

#### Alternative: Using Google Gemini

```json
{
  "mcpServers": {
    "slack-typescript": {
      "command": "node",
      "args": ["path/to/your/project/dist/index.js"],
      "env": {
        "SLACK_BOT_TOKEN": "xoxb-your-bot-token-here",
        "SLACK_USER_TOKEN": "xoxp-your-user-token-here",
        "AI_PROVIDER": "gemini",
        "GEMINI_API_KEY": "your-gemini-api-key-here"
      }
    }
  }
}
```

#### Without AI Features (Basic Mode)

```json
{
  "mcpServers": {
    "slack-typescript": {
      "command": "node",
      "args": ["path/to/your/project/dist/index.js"],
      "env": {
        "SLACK_BOT_TOKEN": "xoxb-your-bot-token-here",
        "SLACK_USER_TOKEN": "xoxp-your-user-token-here"
      }
    }
  }
}
```

#### For Development

```json
{
  "mcpServers": {
    "slack-typescript": {
      "command": "npm",
      "args": ["run", "dev"],
      "cwd": "path/to/your/project",
      "env": {
        "SLACK_BOT_TOKEN": "xoxb-your-bot-token-here",
        "SLACK_USER_TOKEN": "xoxp-your-user-token-here",
        "AI_PROVIDER": "openai",
        "OPENAI_API_KEY": "sk-your-openai-api-key-here"
      }
    }
  }
}
```

#### Advanced Configuration with Custom Models

```json
{
  "mcpServers": {
    "slack-typescript": {
      "command": "node",
      "args": ["path/to/your/project/dist/index.js"],
      "env": {
        "SLACK_BOT_TOKEN": "xoxb-your-bot-token-here",
        "SLACK_USER_TOKEN": "xoxp-your-user-token-here",
        "AI_PROVIDER": "openai",
        "OPENAI_API_KEY": "sk-your-openai-api-key-here",
        "OPENAI_MODEL": "gpt-4"
      }
    }
  }
}
```

**Note**: 
- If no AI provider is configured, the system will automatically fall back to basic keyword expansion
- AI features require valid API keys from OpenAI or Google
- The `ai_search_messages` tool will use enhanced AI-powered keyword generation when available

### Available Tools

The server provides the following tools:

#### Channel Operations
- `list_channels(types?, exclude_archived?)` - List all channels in the workspace
- `get_channel_info(channel)` - Get detailed information about a channel
- `create_channel(name, is_private?)` - Create a new channel

#### Message Operations
- `send_message(channel, text, thread_ts?)` - Send a message to a channel
- `get_channel_history(channel, limit?, oldest?)` - Get recent messages from a channel
- `get_thread_messages(channel, thread_ts, limit?, oldest?, latest?)` - **🧵 Get all messages from a specific thread in chronological order (oldest first)**
- `search_messages(query, count?, sort?)` - Basic search for messages in public channels across the workspace
- `ai_search_messages(query, count?, sort?)` - **🔍 AI-powered intelligent search** with automatic keyword expansion in Japanese and English
- `enhanced_ai_search_messages(query, count?, sort?, include_analysis?, detailed_summary?)` - **✨ Advanced AI search** with comprehensive analysis, insights, and AI-generated summaries

#### User Operations
- `get_user_info(user)` - Get information about a user
- `list_users(include_deleted?)` - List all users in the workspace

#### File Operations
- `upload_file(channels, content, filename, title?, initial_comment?)` - Upload a file to channels
- `search_files(query, count?)` - Search for files in the workspace

#### Reaction Operations
- `add_reaction(channel, timestamp, name)` - Add an emoji reaction to a message
- `remove_reaction(channel, timestamp, name)` - Remove an emoji reaction from a message

#### Health Check
- `health_check()` - Check the health and connectivity of the Slack API connection

## Examples

### Sending a Message
```
Send a message to #general saying 'Hello from the TypeScript MCP server!'
```

### Getting Channel History
```
Get the last 5 messages from the #development channel
```

### Searching Messages
```
Search for messages containing 'deployment' in public channels
```

### Creating a Channel
```
Create a new channel called 'mcp-testing-ts' for testing the TypeScript MCP integration
```

## Development

### Scripts

- `npm run build` - Build the TypeScript code
- `npm run dev` - Run in development mode with hot reloading
- `npm start` - Run the built server
- `npm run watch` - Run in watch mode
- `npm run clean` - Clean the build directory
- `npm run lint` - Run ESLint
- `npm run lint:fix` - Fix ESLint errors
- `npm run demo:ai-search` - Demo basic AI search functionality
- `npm run demo:enhanced-ai-search` - Demo enhanced AI search with analytics

### Project Structure

```
src/
├── index.ts              # Main entry point
├── slack-mcp-server.ts   # Core server implementation
└── types.ts              # TypeScript type definitions
```

## Error Handling

The server includes comprehensive error handling for:
- Invalid Slack tokens
- Rate limiting with exponential backoff
- Network connectivity issues
- Invalid channel/user IDs
- Permission errors

## Security Considerations

## 🔒 Security & Best Practices

**⚠️ IMPORTANT: Token Security**

This MCP server requires sensitive Slack tokens. Follow these security guidelines:

### Token Management
- **Never commit tokens to version control**: Always use environment variables
- **Use secure tokens only**: 
  - Bot Token (`xoxb-*`): For most operations
  - User Token (`xoxp-*`): For search functionality (requires `search:read` scope)
- **Rotate tokens regularly**: Replace tokens periodically for enhanced security
- **Monitor token usage**: Review bot activity in your Slack workspace admin panel

### Environment Setup
1. **Copy `.env.example` to `.env`**:
   ```bash
   cp .env.example .env
   ```

2. **Configure your tokens**:
   ```bash
   # Required for basic functionality
   SLACK_BOT_TOKEN=xoxb-your-actual-bot-token-here
   
   # Required for search functionality  
   SLACK_USER_TOKEN=xoxp-your-actual-user-token-here
   
   # Optional: AI provider for enhanced search
   AI_PROVIDER=openai
   OPENAI_API_KEY=sk-your-openai-key-here
   ```

3. **Verify `.env` is in `.gitignore`**: Ensure your environment file is never committed

### Permissions & Scopes
Grant minimal required permissions:
- **Bot Token Scopes**: `channels:read`, `chat:write`, `files:read`, `users:read`
- **User Token Scopes**: `search:read` (only if search functionality needed)

### Production Deployment
- Use secure secret management systems (AWS Secrets Manager, Azure Key Vault, etc.)
- Implement proper access controls and monitoring
- Consider using dedicated service accounts
- Store your Slack Bot Token securely and never commit it to version control
- Use environment variables or secure secret management
- Regularly rotate your bot tokens
- Monitor bot activity in your Slack workspace
- Grant only the minimum required permissions

## TypeScript Features

This implementation takes advantage of TypeScript's type safety:
- Strict type checking for all Slack API responses
- Interface definitions for all data structures
- Comprehensive error handling with proper typing
- Full IntelliSense support for development

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Run `npm run lint` to check code style
6. Submit a pull request

## Acknowledgments

Special thanks to [MNizarSall/Slack-MCP](https://github.com/MNizarSall/Slack-MCP) for providing inspiration and foundational concepts that influenced this TypeScript implementation. This project builds upon ideas from that excellent implementation while adding enhanced AI capabilities and comprehensive TypeScript support.

## License

This project is licensed under the MIT License.

## Support

For issues and questions:
1. Check the [Slack API documentation](https://api.slack.com/)
2. Review the [MCP specification](https://modelcontextprotocol.io/)
3. Open an issue in this repository