# Wolai MCP Server

A Model Context Protocol (MCP) server for accessing Wolai workspace content, enabling AI assistants to read and interact with your Wolai databases and blocks.

[![npm version](https://img.shields.io/npm/v/wolai-mcp.svg)](https://www.npmjs.com/package/wolai-mcp)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

[简体中文](README.md) | English

## Vibe Coding Statement

This project follows the vibe coding workflow, co-created through human-AI collaboration. It emphasizes immersive rhythm and instant feedback rather than traditional manual coding. Code, documentation, and tests are iteratively generated in this collaborative environment. Please consider this creative context when contributing or reviewing.

## Features

- 🔐 **Authentication**: Automatic token management with Wolai Open API
- 📊 **Database Access**: Read database schemas, rows, and convert to Markdown tables
- 📝 **Block Operations**: Access blocks and their children with hierarchical navigation
- 📄 **Markdown Export**: Convert Wolai content to Obsidian-friendly Markdown format
- ✍️ **Safe Write APIs**: Create blocks or insert database rows with built-in safety prompts
- 🔄 **Pagination Support**: Handle large datasets with cursor-based pagination
- 🛠️ **MCP Tools**: 7 tools for common Wolai operations
- 📦 **MCP Resources**: 2 resource templates for direct URI-based access

## Installation

### Via npm (recommended)

```bash
npm install -g wolai-mcp
```

### From source

```bash
git clone https://github.com/Nita121388/wolai-mcp.git
cd wolai-mcp
npm install
npm run build
```

## Configuration

### Environment Variables

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

```env
WOLAI_APP_ID=your_app_id_here
WOLAI_APP_SECRET=your_app_secret_here
WOLAI_ROOT_BLOCK_ID=your_root_block_id (optional, for default operations)
WOLAI_API_BASE_URL=https://openapi.wolai.com/v1 (optional)
```

To get your Wolai API credentials:
1. Visit [Wolai Open Platform](https://www.wolai.com/wolai/eseF6yB4VzfwxM3M6xWfb2)
2. Create a new application
3. Copy your App ID and App Secret

### MCP Client Configuration

Add to your MCP client configuration (e.g., Claude Desktop):

```json
{
  "mcpServers": {
    "wolai": {
      "command": "npx",
      "args": ["wolai-mcp"],
      "env": {
        "WOLAI_APP_ID": "your_app_id",
        "WOLAI_APP_SECRET": "your_app_secret",
        "WOLAI_ROOT_BLOCK_ID": "your_root_block_id" // optional
      }
    }
  }
}
```

Or if installed globally:

```json
{
  "mcpServers": {
    "wolai": {
      "command": "node",
      "args": ["/path/to/global/node_modules/wolai-mcp/dist/index.js"],
      "env": {
        "WOLAI_APP_ID": "your_app_id",
        "WOLAI_APP_SECRET": "your_app_secret"
      }
    }
  }
}
```

## MCP Tools

| Tool | Description | Parameters |
| --- | --- | --- |
| `wolai_refresh_token` | Refresh the Wolai access token | None |
| `wolai_list_databases` | List databases under a parent block | `parentBlockId` (optional) |
| `wolai_get_database` | Get database schema and rows (auto file-offloading for large datasets) | `databaseId`, `sampleSize`, `includeMeta`, `outputMode` |
| `wolai_get_block` | Get block details and JSON snapshot | `blockId` |
| `wolai_list_block_children` | List children of a block | `blockId`, `page_size`, `start_cursor`, `includeTypes` |
| `wolai_create_block` | Create a block under a parent block (write operation) | `parentId`, `block`, `extra` |
| `wolai_insert_database_row` | Insert one or more rows into a database (write operation) | `databaseId`, `row`/`rows`, `extra` |

> ⚠️ **Write tools** directly modify your Wolai workspace. Always verify payloads on a small scope first, ensure the MCP app has explicit permission on the target page/database, and prefer `outputMode="file"` when previewing large datasets to avoid blocking your MCP client.

## MCP Resources

| Resource URI | Description |
| --- | --- |
| `wolai://database/{databaseId}` | Access database schema and rows |
| `wolai://block/{blockId}` | Access block content and metadata |

## Usage Examples

### Using with Claude Desktop

Once configured, you can interact with your Wolai workspace naturally:

```
User: Show me all databases in my workspace
Claude: [Uses wolai_list_databases tool]

User: Get the content of database XYZ123
Claude: [Uses wolai://database/XYZ123 resource]

User: List the children of block ABC456
Claude: [Uses wolai_list_block_children tool]
```

### Output Format

Each tool returns two formats:
1. **JSON**: Structured data with complete information
2. **Markdown**: Formatted tables ready for copy-paste to Obsidian/Notion

Example output:
````
```json
{
  "schema": {...},
  "rows": [...]
}
```

# Database: Project Tasks

| ID | Title | Status | Priority |
| --- | --- | --- | --- |
| 1 | Task 1 | Done | High |
| 2 | Task 2 | In Progress | Medium |
````

## Development

### Running Tests

```bash
npm test
```

### Local Development

```bash
npm run dev
```

### Building

```bash
npm run build
```

## Project Structure

```
wolai-mcp/
├── src/
│   ├── lib/
│   │   ├── wolaiClient.ts          # Wolai API client
│   │   ├── runtimeConfig.ts        # Configuration management
│   │   └── renderers/
│   │       └── markdownRenderer.ts # Markdown conversion
│   ├── server/
│   │   ├── mcpServer.ts            # MCP server setup
│   │   ├── databaseResource.ts     # Database operations
│   │   └── blockResource.ts        # Block operations
│   └── index.ts                    # Entry point
├── tests/                          # Unit tests
├── docs/                           # Documentation
└── dist/                           # Compiled output
```

## Troubleshooting

### "Missing WOLAI_APP_ID or WOLAI_APP_SECRET"

Make sure your environment variables are properly set in your MCP client configuration.

### "Missing parent block id" or "blockId is required"

This occurs when:
1. You use `wolai_list_databases` without providing `parentBlockId` parameter
2. You use `wolai_list_block_children` without providing `blockId` parameter
3. You access `wolai://block/` resources without specifying a blockId

**Solutions:**
- Provide the required parameter in your requests
- Or set `WOLAI_ROOT_BLOCK_ID` environment variable for a default block
- Example: `wolai_list_databases({ parentBlockId: "your_block_id" })`

### "Path matcher not found" errors

Ensure you're using the latest version after fixing the database rows endpoint issue. Restart your MCP client after updating.

### Token expiration

Use the `wolai_refresh_token` tool to manually refresh if you encounter authentication errors.

### Performance and Large Datasets

The plugin includes several performance optimizations to handle large databases:

- **Auto-pagination**: Large datasets are automatically paginated (default 100 rows per request)
- **Timeout protection**: 30-second timeout prevents requests from hanging
- **Smart sampling**: Use `sampleSize` parameter to preview large databases
- **Cursor support**: Use `cursor` from previous responses to get more rows

Example for large databases:
```javascript
// Get first 50 rows
wolai_get_database({ databaseId: "xxx", limit: 50 })

// Get next page using cursor
wolai_get_database({ databaseId: "xxx", limit: 50, cursor: "from_previous_response" })

// Preview with sampling
wolai_get_database({ databaseId: "xxx", sampleSize: 10 })
```

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

MIT License - see [LICENSE](LICENSE) file for details

## Links

- [Wolai Open Platform](https://www.wolai.com/wolai/eseF6yB4VzfwxM3M6xWfb2)
- [Model Context Protocol](https://modelcontextprotocol.io)
- [GitHub Repository](https://github.com/yourusername/wolai-mcp)

## Roadmap

- [ ] CLI tool for direct command-line access
- [ ] Batch export of multiple databases
- [ ] Attachment download support
- [ ] Caching layer for reduced API calls
- [ ] Rate limiting strategies
