MCP Funcional

This commit is contained in:
Magdiel Cardoso 2025-04-02 13:12:57 -03:00
commit c6cbb2f7ac
21 changed files with 10444 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
node_modules
.wrangler
.env

21
Dockerfile Normal file
View File

@ -0,0 +1,21 @@
FROM node:18-alpine
WORKDIR /app
# Copiar arquivos do projeto
COPY package*.json ./
COPY tsconfig.json ./
COPY wrangler.toml ./
COPY src ./src
# Instalar dependências
RUN npm install
# Compilar TypeScript
RUN npm run build
# Expor a porta
EXPOSE 8787
# Comando para iniciar o servidor
CMD ["npm", "run", "start"]

182
README.md Normal file
View File

@ -0,0 +1,182 @@
# Chatwoot MCP Server
Este é um servidor MCP (Model Context Protocol) que fornece ferramentas para interagir com a API do Chatwoot.
## Ferramentas Disponíveis
1. `chatwoot_setup`: Configura a conexão com o Chatwoot
- Parâmetros:
- `baseUrl`: URL base da sua instalação do Chatwoot
- `apiToken`: Token de API do Chatwoot
2. `chatwoot_list_inboxes`: Lista todas as caixas de entrada
- Sem parâmetros
3. `chatwoot_list_conversations`: Lista conversas
- Parâmetros opcionais:
- `inbox_id`: ID da caixa de entrada
- `status`: Status das conversas ("open", "resolved", "pending")
4. `chatwoot_send_message`: Envia uma mensagem
- Parâmetros:
- `conversation_id`: ID da conversa
- `message`: Conteúdo da mensagem
- `message_type`: Tipo da mensagem ("incoming" ou "outgoing")
5. `chatwoot_update_conversation`: Atualiza o status de uma conversa
- Parâmetros:
- `conversation_id`: ID da conversa
- `status`: Novo status ("open", "resolved", "pending")
## Instalação
### Desenvolvimento Local
1. Clone o repositório
2. Instale as dependências:
```bash
npm install
```
3. Inicie o servidor de desenvolvimento:
```bash
npm run start
```
### Deploy com Docker
1. Clone o repositório
2. Construa e inicie os containers:
```bash
docker-compose up -d
```
O servidor estará disponível em `http://localhost:8787/sse`.
## Uso com Clientes MCP
1. Conecte-se ao servidor usando a URL: `http://seu-servidor:8787/sse`
2. Configure o cliente usando a ferramenta `chatwoot_setup`
3. Comece a usar as outras ferramentas disponíveis
## Exemplo de Uso
```typescript
// Configurar o cliente
await mcp.invoke("chatwoot_setup", {
baseUrl: "https://seu-chatwoot.com",
apiToken: "seu-token-api"
});
// Listar caixas de entrada
const inboxes = await mcp.invoke("chatwoot_list_inboxes");
// Listar conversas abertas
const conversations = await mcp.invoke("chatwoot_list_conversations", {
status: "open"
});
// Enviar mensagem
await mcp.invoke("chatwoot_send_message", {
conversation_id: 123,
message: "Olá! Como posso ajudar?",
message_type: "outgoing"
});
```
## Connect the MCP inspector to your server
To explore your new MCP api, you can use the [MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector).
- Start it with `npx @modelcontextprotocol/inspector`
- [Within the inspector](http://localhost:5173), switch the Transport Type to `SSE` and enter `http://localhost:8787/sse` as the URL of the MCP server to connect to, and click "Connect"
- You will navigate to a (mock) user/password login screen. Input any email and pass to login.
- You should be redirected back to the MCP Inspector and you can now list and call any defined tools!
<div align="center">
<img src="img/mcp-inspector-sse-config.png" alt="MCP Inspector with the above config" width="600"/>
</div>
<div align="center">
<img src="img/mcp-inspector-successful-tool-call.png" alt="MCP Inspector with after a tool call" width="600"/>
</div>
## Connect Claude Desktop to your local MCP server
The MCP inspector is great, but we really want to connect this to Claude! Follow [Anthropic's Quickstart](https://modelcontextprotocol.io/quickstart/user) and within Claude Desktop go to Settings > Developer > Edit Config to find your configuration file.
Open the file in your text editor and replace it with this configuration:
```json
{
"mcpServers": {
"math": {
"command": "npx",
"args": [
"mcp-remote",
"http://localhost:8787/sse"
]
}
}
}
```
This will run a local proxy and let Claude talk to your MCP server over HTTP
When you open Claude a browser window should open and allow you to login. You should see the tools available in the bottom right. Given the right prompt Claude should ask to call the tool.
<div align="center">
<img src="img/available-tools.png" alt="Clicking on the hammer icon shows a list of available tools" width="600"/>
</div>
<div align="center">
<img src="img/claude-does-math-the-fancy-way.png" alt="Claude answers the prompt 'I seem to have lost my calculator and have run out of fingers. Could you use the math tool to add 23 and 19?' by invoking the MCP add tool" width="600"/>
</div>
## Deploy to Cloudflare
1. `npx wrangler kv namespace create OAUTH_KV`
2. Follow the guidance to add the kv namespace ID to `wrangler.jsonc`
3. `npm run deploy`
## Call your newly deployed remote MCP server from a remote MCP client
Just like you did above in "Develop locally", run the MCP inspector:
`npx @modelcontextprotocol/inspector@latest`
Then enter the `workers.dev` URL (ex: `worker-name.account-name.workers.dev/sse`) of your Worker in the inspector as the URL of the MCP server to connect to, and click "Connect".
You've now connected to your MCP server from a remote MCP client.
## Connect Claude Desktop to your remote MCP server
Update the Claude configuration file to point to your `workers.dev` URL (ex: `worker-name.account-name.workers.dev/sse`) and restart Claude
```json
{
"mcpServers": {
"math": {
"command": "npx",
"args": [
"mcp-remote",
"https://worker-name.account-name.workers.dev/sse"
]
}
}
}
```
## Debugging
Should anything go wrong it can be helpful to restart Claude, or to try connecting directly to your
MCP server on the command line with the following command.
```bash
npx mcp-remote http://localhost:8787/sse
```
In some rare cases it may help to clear the files added to `~/.mcp-auth`
```bash
rm -rf ~/.mcp-auth
```

34
biome.json Normal file
View File

@ -0,0 +1,34 @@
{
"$schema": "https://biomejs.dev/schemas/1.6.2/schema.json",
"organizeImports": {
"enabled": true
},
"files": {
"ignore": ["worker-configuration.d.ts"]
},
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"suspicious": {
"noExplicitAny": "off",
"noDebugger": "off",
"noConsoleLog": "off",
"noConfusingVoidType": "off"
},
"style": {
"noNonNullAssertion": "off"
}
}
},
"formatter": {
"enabled": true,
"indentWidth": 4,
"lineWidth": 100
}
}

10
docker-compose.yml Normal file
View File

@ -0,0 +1,10 @@
version: '3'
services:
chatwoot-mcp:
build: .
ports:
- "8787:8787"
restart: unless-stopped
environment:
- NODE_ENV=production

BIN
img/available-tools.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 466 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 403 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 333 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 486 KiB

BIN
img/mcp-login.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 426 KiB

4086
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

26
package.json Normal file
View File

@ -0,0 +1,26 @@
{
"name": "remote-mcp-server",
"version": "0.0.0",
"private": true,
"scripts": {
"deploy": "wrangler deploy",
"dev": "wrangler dev",
"format": "biome format --write",
"lint:fix": "biome lint --fix",
"start": "wrangler dev",
"cf-typegen": "wrangler types"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20250402.0",
"marked": "^15.0.7",
"typescript": "^5.5.2",
"workers-mcp": "^0.1.0-3",
"wrangler": "^4.6.0"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.7.0",
"agents": "^0.0.43",
"hono": "^4.7.4",
"zod": "^3.24.2"
}
}

148
src/chatwoot-tools.ts Normal file
View File

@ -0,0 +1,148 @@
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
export interface ChatwootConfig {
baseUrl: string;
apiToken: string;
accountId: string;
}
export class ChatwootTools {
private server: McpServer;
private configs: Map<string, ChatwootConfig>;
constructor(server: McpServer) {
this.server = server;
this.configs = new Map();
this.registerTools();
}
private async makeRequest(clientId: string, path: string, options: RequestInit = {}) {
const config = this.configs.get(clientId);
if (!config) {
throw new Error("Cliente não configurado. Use a ferramenta setup primeiro.");
}
const response = await fetch(`${config.baseUrl}${path}`, {
...options,
headers: {
"api_access_token": config.apiToken,
"Content-Type": "application/json",
...options.headers,
},
});
if (!response.ok) {
throw new Error(`Erro na requisição: ${response.status} ${response.statusText}`);
}
return response.json();
}
private registerTools() {
// Ferramenta de setup
this.server.tool(
"chatwoot_setup",
{
baseUrl: z.string(),
apiToken: z.string(),
accountId: z.string(),
},
async ({ baseUrl, apiToken, accountId }, context) => {
const clientId = context.clientId;
this.configs.set(clientId, { baseUrl, apiToken, accountId });
return {
content: [{ type: "text", text: "Configuração salva com sucesso!" }],
};
}
);
// Listar caixas de entrada
this.server.tool(
"chatwoot_list_inboxes",
{},
async (_, context) => {
const config = this.configs.get(context.clientId);
const inboxes = await this.makeRequest(context.clientId, `/api/v1/accounts/${config.accountId}/inboxes`);
return {
content: [{ type: "text", text: JSON.stringify(inboxes, null, 2) }],
};
}
);
// Listar conversas
this.server.tool(
"chatwoot_list_conversations",
{
inbox_id: z.number().optional(),
status: z.enum(["open", "resolved", "pending"]).optional(),
},
async ({ inbox_id, status }, context) => {
const config = this.configs.get(context.clientId);
let path = `/api/v1/accounts/${config.accountId}/conversations`;
const params = new URLSearchParams();
if (inbox_id) params.append("inbox_id", inbox_id.toString());
if (status) params.append("status", status);
if (params.toString()) {
path += `?${params.toString()}`;
}
const conversations = await this.makeRequest(context.clientId, path);
return {
content: [{ type: "text", text: JSON.stringify(conversations, null, 2) }],
};
}
);
// Enviar mensagem
this.server.tool(
"chatwoot_send_message",
{
conversation_id: z.number(),
message: z.string(),
message_type: z.enum(["incoming", "outgoing"]).default("outgoing"),
},
async ({ conversation_id, message, message_type }, context) => {
const config = this.configs.get(context.clientId);
const response = await this.makeRequest(
context.clientId,
`/api/v1/accounts/${config.accountId}/conversations/${conversation_id}/messages`,
{
method: "POST",
body: JSON.stringify({
content: message,
message_type,
}),
}
);
return {
content: [{ type: "text", text: JSON.stringify(response, null, 2) }],
};
}
);
// Atualizar status da conversa
this.server.tool(
"chatwoot_update_conversation",
{
conversation_id: z.number(),
status: z.enum(["open", "resolved", "pending"]),
},
async ({ conversation_id, status }, context) => {
const config = this.configs.get(context.clientId);
const response = await this.makeRequest(
context.clientId,
`/api/v1/accounts/${config.accountId}/conversations/${conversation_id}`,
{
method: "PATCH",
body: JSON.stringify({ status }),
}
);
return {
content: [{ type: "text", text: JSON.stringify(response, null, 2) }],
};
}
);
}
}

18
src/index.ts Normal file
View File

@ -0,0 +1,18 @@
import app from "./app";
import { McpAgent } from "agents/mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { ChatwootTools } from "./chatwoot-tools";
export class MyMCP extends McpAgent {
server = new McpServer({
name: "Chatwoot MCP",
version: "1.0.0",
});
async init() {
// Inicializa as ferramentas do Chatwoot
new ChatwootTools(this.server);
}
}
export default MyMCP.mount("/sse");

117
static/README.md Normal file
View File

@ -0,0 +1,117 @@
# Remote MCP Server on Cloudflare
Let's get a remote MCP server up-and-running on Cloudflare Workers complete with OAuth login!
## Develop locally
```bash
# clone the repository
git clone git@github.com:cloudflare/ai.git
# install dependencies
cd ai
npm install
# run locally
npx nx dev remote-mcp-server
```
You should be able to open [`http://localhost:8787/`](http://localhost:8787/) in your browser
## Connect the MCP inspector to your server
To explore your new MCP api, you can use the [MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector).
- Start it with `npx @modelcontextprotocol/inspector`
- [Within the inspector](http://localhost:5173), switch the Transport Type to `SSE` and enter `http://localhost:8787/sse` as the URL of the MCP server to connect to, and click "Connect"
- You will navigate to a (mock) user/password login screen. Input any email and pass to login.
- You should be redirected back to the MCP Inspector and you can now list and call any defined tools!
<div align="center">
<img src="img/mcp-inspector-sse-config.png" alt="MCP Inspector with the above config" width="600"/>
</div>
<div align="center">
<img src="img/mcp-inspector-successful-tool-call.png" alt="MCP Inspector with after a tool call" width="600"/>
</div>
## Connect Claude Desktop to your local MCP server
The MCP inspector is great, but we really want to connect this to Claude! Follow [Anthropic's Quickstart](https://modelcontextprotocol.io/quickstart/user) and within Claude Desktop go to Settings > Developer > Edit Config to find your configuration file.
Open the file in your text editor and replace it with this configuration:
```json
{
"mcpServers": {
"math": {
"command": "npx",
"args": [
"mcp-remote",
"http://localhost:8787/sse"
]
}
}
}
```
This will run a local proxy and let Claude talk to your MCP server over HTTP
When you open Claude a browser window should open and allow you to login. You should see the tools available in the bottom right. Given the right prompt Claude should ask to call the tool.
<div align="center">
<img src="img/available-tools.png" alt="Clicking on the hammer icon shows a list of available tools" width="600"/>
</div>
<div align="center">
<img src="img/claude-does-math-the-fancy-way.png" alt="Claude answers the prompt 'I seem to have lost my calculator and have run out of fingers. Could you use the math tool to add 23 and 19?' by invoking the MCP add tool" width="600"/>
</div>
## Deploy to Cloudflare
1. `npx wrangler@latest kv namespace create remote-mcp-server-oauth-kv`
2. Follow the guidance to add the kv namespace ID to `wrangler.jsonc`
3. `npm run deploy`
## Call your newly deployed remote MCP server from a remote MCP client
Just like you did above in "Develop locally", run the MCP inspector:
`npx @modelcontextprotocol/inspector@latest`
Then enter the `workers.dev` URL (ex: `worker-name.account-name.workers.dev/sse`) of your Worker in the inspector as the URL of the MCP server to connect to, and click "Connect".
You've now connected to your MCP server from a remote MCP client.
## Connect Claude Desktop to your remote MCP server
Update the Claude configuration file to point to your `workers.dev` URL (ex: `worker-name.account-name.workers.dev/sse`) and restart Claude
```json
{
"mcpServers": {
"math": {
"command": "npx",
"args": [
"mcp-remote",
"https://worker-name.account-name.workers.dev/sse"
]
}
}
}
```
## Debugging
Should anything go wrong it can be helpful to restart Claude, or to try connecting directly to your
MCP server on the command line with the following command.
```bash
npx mcp-remote http://localhost:8787/sse
```
In some rare cases it may help to clear the files added to `~/.mcp-auth`
```bash
rm -rf ~/.mcp-auth
```

1
static/img Symbolic link
View File

@ -0,0 +1 @@
/var/folders/nh/288y8gdn779538kspr78mzbr0000gn/T/c3-templatemMccjB/img

22
tsconfig.json Normal file
View File

@ -0,0 +1,22 @@
{
"compilerOptions": {
"target": "es2021",
"lib": ["es2021"],
"jsx": "react-jsx",
"module": "es2022",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"allowJs": true,
"checkJs": false,
"noEmit": true,
"isolatedModules": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"types": [
"@cloudflare/workers-types/2023-07-01"
]
},
"include": ["worker-configuration.d.ts", "src/**/*.ts"]
}

5709
worker-configuration.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

67
wrangler.jsonc Normal file
View File

@ -0,0 +1,67 @@
/**
* For more details on how to configure Wrangler, refer to:
* https://developers.cloudflare.com/workers/wrangler/configuration/
*/
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "chatwoot-mcp",
"main": "src/index.ts",
"compatibility_date": "2025-03-10",
"migrations": [
{
"new_sqlite_classes": [
"MyMCP"
],
"tag": "v1"
}
],
"durable_objects": {
"bindings": [
{
"class_name": "MyMCP",
"name": "MCP_OBJECT"
}
]
},
"observability": {
"enabled": true
},
"assets": {
"directory": "./static/",
"binding": "ASSETS"
}
/**
* Smart Placement
* Docs: https://developers.cloudflare.com/workers/configuration/smart-placement/#smart-placement
*/
// "placement": { "mode": "smart" },
/**
* Bindings
* Bindings allow your Worker to interact with resources on the Cloudflare Developer Platform, including
* databases, object storage, AI inference, real-time communication and more.
* https://developers.cloudflare.com/workers/runtime-apis/bindings/
*/
/**
* Environment Variables
* https://developers.cloudflare.com/workers/wrangler/configuration/#environment-variables
*/
// "vars": { "MY_VARIABLE": "production_value" },
/**
* Note: Use secrets to store sensitive data.
* https://developers.cloudflare.com/workers/configuration/secrets/
*/
/**
* Static Assets
* https://developers.cloudflare.com/workers/static-assets/binding/
*/
// "assets": { "directory": "./public/", "binding": "ASSETS" },
/**
* Service Bindings (communicate between multiple Workers)
* https://developers.cloudflare.com/workers/wrangler/configuration/#service-bindings
*/
// "services": [{ "binding": "MY_SERVICE", "service": "my-service" }]
}