@tiledesk/tiledesk-server 3.3.5 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/app.js +7 -0
- package/docs/activities-client.md +27 -0
- package/docs/mcp-oauth2-it.md +279 -0
- package/docs/mcp-oauth2.md +279 -0
- package/docs/superpowers/plans/2026-11-10-mcp-oauth2-server-it.md +155 -0
- package/docs/superpowers/plans/2026-11-10-mcp-oauth2-server.md +155 -0
- package/docs/superpowers/plans/2026-11-10-mcp-oauth2-tybot-it.md +63 -0
- package/docs/superpowers/plans/2026-11-10-mcp-oauth2-tybot.md +63 -0
- package/docs/superpowers/specs/2026-11-10-mcp-oauth2-design-it.md +207 -0
- package/docs/superpowers/specs/2026-11-10-mcp-oauth2-design.md +207 -0
- package/jobs.js +15 -0
- package/models/mcpOAuthConnection.js +131 -0
- package/package.json +1 -1
- package/pubmodules/activities/activityMessageUtil.js +137 -0
- package/pubmodules/activities/models/activity.js +2 -0
- package/pubmodules/activities/routes/activity.js +30 -1
- package/pubmodules/activities/test/execution-filter.test.js +133 -0
- package/pubmodules/activities/test/execution-messages.test.js +158 -0
- package/pubmodules/executions-publisher/index.js +457 -0
- package/pubmodules/executions-publisher/test/audit-consumer.test.js +384 -0
- package/pubmodules/executions-publisher/test/executions-publisher.test.js +204 -0
- package/pubmodules/pubModulesManager.js +12 -0
- package/routes/executions-refire.js +148 -0
- package/routes/mcp.js +11 -8
- package/routes/mcpOAuth.js +133 -0
- package/routes/mcpOAuthCallback.js +75 -0
- package/routes/request.js +5 -0
- package/routes/webhook.js +120 -54
- package/services/mcpOAuthDiscovery.js +248 -0
- package/services/mcpOAuthGoogleScopes.js +55 -0
- package/services/mcpOAuthService.js +732 -0
- package/services/mcpService.js +111 -15
- package/services/requestService.js +4 -2
- package/services/webhookService.js +4 -2
- package/test/executions-refire.test.js +362 -0
- package/test/mcpOAuthDiscovery.test.js +331 -0
- package/test/mcpOAuthGoogleScopes.test.js +25 -0
- package/test/mcpOAuthRoute.test.js +455 -0
- package/test/mcpOAuthService.test.js +693 -0
- package/test/mcpOAuthUtils.test.js +348 -0
- package/test/mcpServiceOAuth.test.js +267 -0
- package/test/requestRoute.js +57 -0
- package/test/webhookConversationRoute.js +51 -0
- package/utils/logRedactor.js +4 -2
- package/utils/mcpOAuthCrypto.js +69 -0
- package/utils/mcpOAuthPkce.js +20 -0
- package/utils/outboundUrlGuard.js +131 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,23 @@
|
|
|
5
5
|
🚀 IN PRODUCTION 🚀
|
|
6
6
|
(https://www.npmjs.com/package/@tiledesk/tiledesk-server/v/2.3.77)
|
|
7
7
|
|
|
8
|
+
# 3.5.0
|
|
9
|
+
- MCP OAuth2: MCP servers protected by OAuth2 can be connected with the authorization code flow and PKCE. Three modes: `mcp` discovers the authorization server from the MCP server (401 `WWW-Authenticate`, protected resource metadata, authorization server metadata) and registers the client dynamically; `google` uses the Tiledesk Google OAuth client; `manual` takes the endpoints and client from the request. Tokens and client secrets are stored encrypted (AES-256-GCM) in the new `mcp_oauth_connections` collection, one connection per project and server URL
|
|
10
|
+
- New `POST /:projectid/mcp/oauth/authorize` (admin) `{ mode, server_url, name?, scopes?, return_url?, manual? }` answers `{ authorization_url, connection_id }`. The provider redirects to the new public `GET /oauth2/mcp/callback`, which completes the connection and redirects to `return_url` with `mcp_oauth=success|error&connection_id=`, or shows a page when no `return_url` was given. The `state` is single use and lasts 10 minutes; `return_url` must belong to `MCP_OAUTH_RETURN_ORIGINS`
|
|
11
|
+
- New `GET /:projectid/mcp/oauth/connections`, `GET …/connections/:id`, `POST …/connections/:id/refresh` and `DELETE …/connections/:id` (admin). They never return tokens or client credentials. Deleting revokes the tokens at the provider when it can and removes `oauth` from the MCP integration entries that used the connection; the entries stay, without authentication
|
|
12
|
+
- New `GET /:projectid/mcp/oauth/connections/:id/token` for chatbots and subscriptions of the project only: dashboard users, admins included, get 403. It answers `{ access_token, token_type, expires_at }` and refreshes the token first when it expires within 5 minutes. Concurrent refreshes of one connection are serialized through a Redis lock, so the provider sees one refresh even with several server instances. A connection whose refresh token was rejected moves to `needs_reauth` and answers 409 until it is authorized again
|
|
13
|
+
- New `POST /webhook/mcp-oauth/refresh` for the scheduler, authenticated by the `x-auth-token` header against `MCP_OAUTH_REFRESH_TOKEN`: `{ connection_id }` refreshes one connection, `{ within_seconds }` (60..86400, default 900) refreshes every connection expiring within the window and answers `{ refreshed, failed, needs_reauth }`
|
|
14
|
+
- `POST /:projectid/mcp/connect`, `/mcp/tools` and `/mcp/servers` accept `oauth: { connection_id }`: requests to the MCP server carry the connection's bearer token, which overrides any `Authorization` header in `customHeaders`, and a 401 from the server triggers one refresh and one retry. The token is sent only to the server URL the connection was authorized for (400 otherwise); saved entries keep `oauth: { connection_id, mode }` and never the token. Native MCP servers do not accept `oauth` yet (400). The old `oauth: { clientId, … }` object is still rejected
|
|
15
|
+
- In `google` mode `scopes` is optional for the Google MCP servers (Gmail, Drive, Docs, Sheets, Slides, Calendar, Chat, People, Classroom, BigQuery): when it is missing, the scopes documented by Google for that server are requested. Other Google URLs without `scopes` still answer 400
|
|
16
|
+
- Outbound OAuth calls (discovery, registration, token, revocation) refuse private, loopback and link-local addresses, including after DNS resolution, follow no redirects and time out after 10 seconds. `MCP_OAUTH_ALLOW_INSECURE_URLS=true` lifts the https and address checks, for local development only
|
|
17
|
+
- New environment variables: `MCP_OAUTH_ENCRYPTION_KEY` (32 bytes, base64; without it every MCP OAuth route answers 503), `MCP_OAUTH_REDIRECT_BASE_URL` (defaults to `API_URL`), `MCP_OAUTH_RETURN_ORIGINS`, `MCP_OAUTH_GOOGLE_CLIENT_ID`, `MCP_OAUTH_GOOGLE_CLIENT_SECRET`, `MCP_OAUTH_REFRESH_TOKEN`, `MCP_OAUTH_ALLOW_INSECURE_URLS`
|
|
18
|
+
|
|
19
|
+
# 3.4.0
|
|
20
|
+
- Added agent execution traceability support (off unless `EXECUTIONS_AMQP_URL` is set): the server publishes conversation events and conversation ends (also from the jobs worker) to the executions service, and a replace can carry a subagent reason
|
|
21
|
+
- Added: the executions audit (pause, resume, destroy, start new, data access, retention and pause notice changes) is mirrored into Activities as owner-only rows; requested and data_viewed audits get no row; execution short ids are the uuid's random tail
|
|
22
|
+
- Added: refire route for automations (resume / start new); public webhook routes drop a caller's `retry_of`; an automation refire never waits for the flow
|
|
23
|
+
- Fixed: the audit consumer drops unsavable messages and requeues the recoverable save errors; rejected controls read as attempts; `closed_by` is null when unset; AMQP connect timeout
|
|
24
|
+
|
|
8
25
|
# 3.3.5
|
|
9
26
|
- Bumped tybot-connector version to 3.0.8
|
|
10
27
|
|
package/app.js
CHANGED
|
@@ -97,6 +97,8 @@ tdCache.connect();
|
|
|
97
97
|
|
|
98
98
|
const mcpService = require('./services/mcpService');
|
|
99
99
|
mcpService.setTdCache(tdCache);
|
|
100
|
+
const mcpOAuthService = require('./services/mcpOAuthService');
|
|
101
|
+
mcpOAuthService.setTdCache(tdCache);
|
|
100
102
|
|
|
101
103
|
// ROUTES DECLARATION
|
|
102
104
|
var troubleshooting = require('./routes/troubleshooting');
|
|
@@ -157,9 +159,11 @@ var segment = require('./routes/segment');
|
|
|
157
159
|
var dataTable = require('./routes/dataTable');
|
|
158
160
|
var webhook = require('./routes/webhook');
|
|
159
161
|
var webhooks = require('./routes/webhooks');
|
|
162
|
+
var executionsRefire = require('./routes/executions-refire');
|
|
160
163
|
var roles = require('./routes/roles');
|
|
161
164
|
var copilot = require('./routes/copilot');
|
|
162
165
|
var mcp = require('./routes/mcp');
|
|
166
|
+
var mcpOAuthCallback = require('./routes/mcpOAuthCallback');
|
|
163
167
|
var agentPrompts = require('./routes/agentPrompts');
|
|
164
168
|
|
|
165
169
|
var bootDataLoader = require('./services/bootDataLoader');
|
|
@@ -544,6 +548,7 @@ var projectSetter = function (req, res, next) {
|
|
|
544
548
|
|
|
545
549
|
app.use('/troubleshooting', troubleshooting);
|
|
546
550
|
app.use('/auth', auth);
|
|
551
|
+
app.use('/oauth2/mcp', mcpOAuthCallback);
|
|
547
552
|
app.use('/testauth', [passport.authenticate(['basic', 'jwt'], { session: false }), validtoken], authtest);
|
|
548
553
|
|
|
549
554
|
app.use('/widgets', widgetsLoader);
|
|
@@ -674,6 +679,8 @@ app.use('/:projectid/kb', [passport.authenticate(['basic', 'jwt'], { session: fa
|
|
|
674
679
|
app.use('/:projectid/logs', [passport.authenticate(['basic', 'jwt'], { session: false }), validtoken, roleChecker.hasRole('agent')], logs);
|
|
675
680
|
|
|
676
681
|
app.use('/:projectid/webhooks', [passport.authenticate(['basic', 'jwt'], { session: false }), validtoken, roleChecker.hasRole('admin')], webhooks);
|
|
682
|
+
// Start new of an agent execution (traceability Phase 3): mounted only with EXECUTIONS_AMQP_URL, needs executions_control.
|
|
683
|
+
executionsRefire.mountIfEnabled(app);
|
|
677
684
|
app.use('/:projectid/copilot', [passport.authenticate(['basic', 'jwt'], { session: false }), validtoken, roleChecker.hasRole('agent')], copilot);
|
|
678
685
|
app.use('/:projectid/roles', [passport.authenticate(['basic', 'jwt'], { session: false }), validtoken, roleChecker.hasRole('agent')], roles);
|
|
679
686
|
|
|
@@ -192,6 +192,33 @@ interface Activity {
|
|
|
192
192
|
|
|
193
193
|
`target.type` = `faq_kb` — nome in `target.object.name` o `actionObj.name`.
|
|
194
194
|
|
|
195
|
+
### Esecuzioni agente (`EXECUTION_*`)
|
|
196
|
+
|
|
197
|
+
Scritte dal consumer di audit (`pubmodules/executions-publisher`, coda `server.executions.audit`, attivo solo con `EXECUTIONS_AMQP_URL`) quando la dashboard ferma, elimina, riprende o riavvia (start new) un'esecuzione. Salvate solo se `ACTIVITY_HISTORY_ENABLED=true`; idempotenti su `actionObj.audit_id` (indice unique sparse). Visibili solo con il permesso `executions_audit_read`.
|
|
198
|
+
|
|
199
|
+
| Verb | Significato | Frase EN | Frase IT |
|
|
200
|
+
|---|---|---|---|
|
|
201
|
+
| `EXECUTION_STOP_SOFT` | Stop soft di un'esecuzione | *X soft-stopped execution `abc123` of Y* | *X ha fermato (soft) l'esecuzione `abc123` di Y* |
|
|
202
|
+
| `EXECUTION_STOP_HARD` | Stop hard | *X hard-stopped execution `abc123` of Y* | *X ha fermato (hard) l'esecuzione `abc123` di Y* |
|
|
203
|
+
| `EXECUTION_DESTROY` | Eliminazione | *X destroyed execution `abc123` of Y* | *X ha eliminato l'esecuzione `abc123` di Y* |
|
|
204
|
+
| `EXECUTION_RESUME` | Ripresa di un'esecuzione ferma o fallita (stesso execution id) | *X resumed execution `abc123` of Y* | *X ha ripreso l'esecuzione `abc123` di Y* |
|
|
205
|
+
| `EXECUTION_START_NEW` | Nuova esecuzione dallo stesso trigger (`retry_of` = `abc123`) | *X started a new run of execution `abc123` of Y* | *X ha avviato una nuova esecuzione da `abc123` di Y* |
|
|
206
|
+
| `EXECUTION_DATA_ACCESS` | Lettura dei dati di un'esecuzione o di un blocco, con motivo (solo `accepted`; i rifiuti non sono riportati) | *X viewed the data of execution `abc123` of Y · "motivo" · 1 block* / *· whole execution* | *X ha visualizzato i dati dell'esecuzione `abc123` di Y · "motivo" · 1 blocco* / *· intera esecuzione* |
|
|
207
|
+
| `EXECUTION_DATA_ACCESS_DENIED` | Accesso ai dati negato per ruolo | *X was denied access to the data of execution `abc123` of Y (role R)* | *X non ha ottenuto l'accesso ai dati dell'esecuzione `abc123` di Y (ruolo R)* |
|
|
208
|
+
| `EXECUTION_RETENTION_UPDATE` | Modifica della conservazione delle esecuzioni (progetto, nessuna esecuzione né agente) | *X changed executions retention: trace 90 → 30 days, data 30 → 7 days* | *X ha modificato la conservazione delle esecuzioni: tracce 90 → 30 giorni, dati 30 → 7 giorni* |
|
|
209
|
+
|
|
210
|
+
Per `EXECUTION_RETENTION_UPDATE` la frase riporta solo le parti cambiate (tracce e/o dati); il `target` è `{ type: "project", id: id_project, object: {} }` e non c'è `related`. `data_viewed` non genera righe. `actionObj` può avere inoltre `scope` = `{ type: "execution" | "step", step_seq? }`, `grant_id`, `role` (solo `EXECUTION_DATA_ACCESS_DENIED`) e `retention` = `{ before: { trace_days, data_days }, after: { trace_days, data_days } }`.
|
|
211
|
+
|
|
212
|
+
Un controllo rifiutato (`actionObj.result` = `rejected:<motivo>`) si legge come tentativo: *X tried to resume execution `abc123` of Y (rejected: not_resumable)* / *X ha provato a riprendere l'esecuzione `abc123` di Y (rifiutato: not_resumable)*; per start new *tried to start a new run of execution* / *ha provato ad avviare una nuova esecuzione da*.
|
|
213
|
+
|
|
214
|
+
`abc123` sono i primi 6 caratteri dell'execution id. Se presente un motivo, la frase termina con ` · "motivo"`. Il CSV usa la frase in `lang=it|en`.
|
|
215
|
+
|
|
216
|
+
- `actor` = `{ type: "user", id, name }`
|
|
217
|
+
- `target` = `{ type: "execution", id: execution_id, object: { agent_id, agent_name, request_id, status_after, trigger_type } }`
|
|
218
|
+
- `related` = `{ role: "agent", type: "faq_kb", id: agent_id, name: agent_name }`
|
|
219
|
+
- `actionObj` = `{ mode?, reason?, result, audit_id }` (`result` = `accepted` | `rejected:<motivo>`)
|
|
220
|
+
- `createdAt` = istante dell'azione (`at` dell'audit)
|
|
221
|
+
|
|
195
222
|
### Knowledge Base — namespace e contenuti
|
|
196
223
|
|
|
197
224
|
| Verb | Significato | Esempio frase (IT) |
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
# MCP OAuth2 — Guida
|
|
2
|
+
|
|
3
|
+
Cosa è stato sviluppato per collegare gli agenti AI di Tiledesk ai server MCP protetti da OAuth2, e quali casi d'uso copre.
|
|
4
|
+
|
|
5
|
+
Versione inglese: [mcp-oauth2.md](mcp-oauth2.md). Design di dettaglio: [superpowers/specs/2026-11-10-mcp-oauth2-design-it.md](superpowers/specs/2026-11-10-mcp-oauth2-design-it.md).
|
|
6
|
+
|
|
7
|
+
## 1. In breve
|
|
8
|
+
|
|
9
|
+
Molti server MCP (Google Workspace, Google Cloud, prodotti SaaS, server interni aziendali) non accettano una API key statica: richiedono OAuth2. L'utente proprietario dei dati deve approvare l'accesso nella pagina del provider, e il client riceve un access token che scade (di solito dopo un'ora) più un refresh token per ottenerne di nuovi.
|
|
10
|
+
|
|
11
|
+
Con questa funzionalità **tiledesk-server fa da client OAuth** per il progetto:
|
|
12
|
+
|
|
13
|
+
- un admin collega il server MCP una volta sola, approvando l'accesso nella pagina del provider;
|
|
14
|
+
- il server salva i token **cifrati** nel database e li **rinnova** quando stanno per scadere;
|
|
15
|
+
- il chatbot (tybot), quando un'azione AI Prompt usa quel server MCP, chiede al server un access token valido e lo invia come `Authorization: Bearer …`.
|
|
16
|
+
|
|
17
|
+
I token non arrivano mai al browser e non vengono mai scritti nelle integrazioni del progetto.
|
|
18
|
+
|
|
19
|
+
## 2. Casi d'uso
|
|
20
|
+
|
|
21
|
+
| # | Caso d'uso | Come |
|
|
22
|
+
|---|---|---|
|
|
23
|
+
| 1 | Server MCP che segue la MCP Authorization spec (discovery + registrazione dinamica del client) | Modalità **`mcp`**: l'admin scrive solo l'URL del server MCP; il server trova il provider OAuth e si registra come client |
|
|
24
|
+
| 2 | Server MCP di Google (Calendar, Gmail, Drive, BigQuery, Cloud Run, …) | Modalità **`google`**: un solo client OAuth Google per tutta l'installazione, configurato da env; gli scope sono facoltativi per i server MCP Google noti (il server usa quelli documentati da Google), obbligatori per gli altri |
|
|
25
|
+
| 3 | Qualsiasi provider OAuth2 senza discovery | Modalità **`manual`**: l'admin inserisce authorization URL, token URL, client ID e secret, scope |
|
|
26
|
+
| 4 | Agente AI che usa un server MCP OAuth in conversazione | tybot chiede `GET /mcp/oauth/connections/:id/token` con il JWT del bot e passa il Bearer al server MCP tramite il backend LLM |
|
|
27
|
+
| 5 | L'admin elenca i tool e salva il server dalla dashboard | `/mcp/connect`, `/mcp/tools` e `/mcp/servers` accettano `oauth: { connection_id }` |
|
|
28
|
+
| 6 | Access token scaduto | Refresh automatico quando il token viene richiesto (lazy) e, se configurato, refresh periodico dallo scheduler |
|
|
29
|
+
| 7 | Accesso revocato dall'utente sul provider, o refresh token scaduto | La connessione passa a `needs_reauth`; l'azione AI Prompt fallisce con "MCP server … needs to be reconnected"; l'admin riconnette |
|
|
30
|
+
| 8 | Scollegare un server | `DELETE` della connessione: revoca sul provider, eliminazione, `oauth` tolto dall'integrazione |
|
|
31
|
+
|
|
32
|
+
Non ancora coperti: OAuth sui server MCP **nativi** (catalogo Tiledesk), token per singolo utente finale (tutte le conversazioni del progetto usano la connessione autorizzata dall'admin), la UI del Design Studio.
|
|
33
|
+
|
|
34
|
+
## 3. Architettura
|
|
35
|
+
|
|
36
|
+
```mermaid
|
|
37
|
+
flowchart LR
|
|
38
|
+
subgraph Browser
|
|
39
|
+
D[Dashboard<br/>Integrations → MCP]
|
|
40
|
+
P[Pagina di consenso<br/>del provider]
|
|
41
|
+
end
|
|
42
|
+
subgraph Tiledesk
|
|
43
|
+
S[tiledesk-server<br/>client OAuth]
|
|
44
|
+
DB[(MongoDB<br/>mcp_oauth_connections<br/>token cifrati)]
|
|
45
|
+
R[(Redis<br/>state, lock di refresh)]
|
|
46
|
+
T[tybot<br/>azione AI Prompt]
|
|
47
|
+
L[Backend LLM]
|
|
48
|
+
SC[scheduler-service]
|
|
49
|
+
end
|
|
50
|
+
subgraph Esterni
|
|
51
|
+
AS[Provider OAuth<br/>Google / auth server MCP / altro]
|
|
52
|
+
M[Server MCP]
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
D -- "authorize, connections, tools" --> S
|
|
56
|
+
D -. apre .-> P
|
|
57
|
+
P -- consenso --> AS
|
|
58
|
+
AS -- "redirect /oauth2/mcp/callback" --> S
|
|
59
|
+
S <-- "code → token, refresh" --> AS
|
|
60
|
+
S --- DB
|
|
61
|
+
S --- R
|
|
62
|
+
T -- "GET …/token (JWT bot)" --> S
|
|
63
|
+
T -- "server + Bearer" --> L
|
|
64
|
+
L -- "chiamate MCP + Bearer" --> M
|
|
65
|
+
S -- "connect / lista tool + Bearer" --> M
|
|
66
|
+
SC -- "POST /webhook/mcp-oauth/refresh" --> S
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
| Componente | Ruolo | Stato |
|
|
70
|
+
|---|---|---|
|
|
71
|
+
| tiledesk-server | Flusso OAuth, salvataggio cifrato, refresh, endpoint del token, API di gestione, webhook per lo scheduler | Fatto, in esecuzione su stage |
|
|
72
|
+
| tiledesk-chatbot (tybot) | Legge `oauth.connection_id` dall'integrazione, ottiene il token, invia il Bearer | Piano di implementazione consegnato |
|
|
73
|
+
| tiledesk-scheduler-service | Target `mcpOAuthRefresh` che chiama il webhook di refresh | Piano di implementazione consegnato |
|
|
74
|
+
| tiledesk-dashboard | Selettore dell'autenticazione, flusso con popup, stato della connessione, riconnessione | Piano di implementazione consegnato |
|
|
75
|
+
|
|
76
|
+
## 4. Componenti del server
|
|
77
|
+
|
|
78
|
+
| File | Contenuto |
|
|
79
|
+
|---|---|
|
|
80
|
+
| `models/mcpOAuthConnection.js` | Collection `mcp_oauth_connections`: una connessione per progetto e URL del server MCP; vista pubblica senza segreti (`toPublic`) |
|
|
81
|
+
| `services/mcpOAuthService.js` | Avvio dell'autorizzazione e callback, scambio del codice, refresh lazy con lock, refresh delle connessioni in scadenza, revoca |
|
|
82
|
+
| `services/mcpOAuthDiscovery.js` | Modalità `mcp`: Protected Resource Metadata (RFC 9728), Authorization Server Metadata (RFC 8414 / OIDC), Dynamic Client Registration (RFC 7591) |
|
|
83
|
+
| `utils/mcpOAuthCrypto.js` | Cifratura AES-256-GCM di token e client secret (formato `v1:`) |
|
|
84
|
+
| `utils/mcpOAuthPkce.js` | Verifier/challenge PKCE S256 e `state` casuale |
|
|
85
|
+
| `utils/outboundUrlGuard.js` | Blocca le chiamate verso URL non https e indirizzi privati/loopback (SSRF) |
|
|
86
|
+
| `routes/mcpOAuth.js` | `/:projectid/mcp/oauth/*`: authorize, connections, refresh, delete, token |
|
|
87
|
+
| `routes/mcpOAuthCallback.js` | `GET /oauth2/mcp/callback` pubblico |
|
|
88
|
+
| `routes/webhook.js` | `POST /webhook/mcp-oauth/refresh` per lo scheduler |
|
|
89
|
+
| `services/mcpService.js` | Chiamate MCP con `oauth.connection_id`: aggiunge il Bearer, dopo un 401 forza un refresh e riprova una volta |
|
|
90
|
+
|
|
91
|
+
## 5. Collegare un server (flusso di autorizzazione)
|
|
92
|
+
|
|
93
|
+
```mermaid
|
|
94
|
+
sequenceDiagram
|
|
95
|
+
autonumber
|
|
96
|
+
actor A as Admin
|
|
97
|
+
participant D as Dashboard
|
|
98
|
+
participant S as tiledesk-server
|
|
99
|
+
participant AS as Provider OAuth
|
|
100
|
+
participant M as Server MCP
|
|
101
|
+
|
|
102
|
+
A->>D: Connect (modalità mcp / google / manual)
|
|
103
|
+
D->>S: POST /:project/mcp/oauth/authorize
|
|
104
|
+
opt modalità mcp
|
|
105
|
+
S->>M: initialize senza token → 401 + resource_metadata
|
|
106
|
+
S->>AS: discovery dei metadata + registrazione del client (DCR)
|
|
107
|
+
end
|
|
108
|
+
S->>S: state + PKCE in Redis (10 min, monouso)
|
|
109
|
+
S-->>D: authorization_url, connection_id
|
|
110
|
+
D->>AS: apre authorization_url (popup)
|
|
111
|
+
A->>AS: login + consenso
|
|
112
|
+
AS->>S: GET /oauth2/mcp/callback?code&state
|
|
113
|
+
S->>AS: code + code_verifier → access + refresh token
|
|
114
|
+
S->>S: token cifrati in MongoDB, stato active
|
|
115
|
+
S-->>A: pagina "Connected" (o redirect a return_url)
|
|
116
|
+
D->>S: POST /mcp/tools { url, oauth: { connection_id } }
|
|
117
|
+
S->>M: tools/list + Bearer
|
|
118
|
+
D->>S: salva il server con oauth.connection_id
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
La voce salvata nell'integrazione contiene solo un riferimento:
|
|
122
|
+
|
|
123
|
+
```json
|
|
124
|
+
{ "name": "Google Calendar", "url": "https://calendarmcp.googleapis.com/mcp/v1",
|
|
125
|
+
"transport": "streamable_http", "tools": [ ... ],
|
|
126
|
+
"oauth": { "connection_id": "6731f0…", "mode": "google" } }
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## 6. Uso del token in conversazione
|
|
130
|
+
|
|
131
|
+
```mermaid
|
|
132
|
+
sequenceDiagram
|
|
133
|
+
autonumber
|
|
134
|
+
participant U as Utente finale
|
|
135
|
+
participant T as tybot (AI Prompt)
|
|
136
|
+
participant S as tiledesk-server
|
|
137
|
+
participant AS as Provider OAuth
|
|
138
|
+
participant L as Backend LLM
|
|
139
|
+
participant M as Server MCP
|
|
140
|
+
|
|
141
|
+
U->>T: messaggio
|
|
142
|
+
T->>S: GET /integration/name/mcp
|
|
143
|
+
T->>S: GET /mcp/oauth/connections/:id/token (JWT bot)
|
|
144
|
+
alt token valido per più di 5 minuti
|
|
145
|
+
S-->>T: access_token
|
|
146
|
+
else in scadenza o scaduto
|
|
147
|
+
S->>AS: grant_type=refresh_token (lock Redis)
|
|
148
|
+
AS-->>S: nuovo access token (e refresh token, se ruotato)
|
|
149
|
+
S-->>T: nuovo access_token
|
|
150
|
+
end
|
|
151
|
+
T->>L: prompt + server MCP con Authorization: Bearer
|
|
152
|
+
L->>M: tools/call + Bearer
|
|
153
|
+
M-->>L: risultato
|
|
154
|
+
L-->>T: risposta
|
|
155
|
+
T-->>U: risposta
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
- L'endpoint del token risponde solo a credenziali **bot o subscription** dello stesso progetto: il JWT di un admin riceve 403, così i token non arrivano mai alla dashboard.
|
|
159
|
+
- tybot tiene il token in memoria fino a 60 secondi prima della scadenza.
|
|
160
|
+
- Se la connessione va riautorizzata (409 `needs_reauth`), l'azione fallisce come se mancasse l'integrazione: `flowError` "MCP server … needs to be reconnected", poi il ramo false dell'azione.
|
|
161
|
+
|
|
162
|
+
## 7. Refresh dei token
|
|
163
|
+
|
|
164
|
+
Due meccanismi, entrambi nel server:
|
|
165
|
+
|
|
166
|
+
1. **Lazy (sempre attivo).** Ogni richiesta di token controlla la scadenza. Se l'access token scade entro 5 minuti viene rinnovato, altrimenti si restituisce quello salvato. Un lock su Redis garantisce che richieste contemporanee, anche da pod diversi, facciano un solo refresh. Un 401 dal server MCP provoca un refresh forzato e un nuovo tentativo.
|
|
167
|
+
2. **Periodico (facoltativo).** Lo scheduler chiama `POST /webhook/mcp-oauth/refresh` con `{ within_seconds }`: il server rinnova le connessioni attive che scadono entro quella finestra. Serve per le connessioni che nessuno usa per giorni (alcuni provider fanno scadere i refresh token inutilizzati) e per scoprire le connessioni revocate prima che una conversazione ci inciampi. Per far funzionare il chatbot basta il meccanismo lazy.
|
|
168
|
+
|
|
169
|
+
```mermaid
|
|
170
|
+
stateDiagram-v2
|
|
171
|
+
[*] --> pending: authorize
|
|
172
|
+
pending --> active: callback ok
|
|
173
|
+
pending --> pending: errore del provider (last_error)
|
|
174
|
+
active --> active: refresh ok
|
|
175
|
+
active --> needs_reauth: invalid_grant (revocato / scaduto)
|
|
176
|
+
needs_reauth --> active: nuova authorize + consenso
|
|
177
|
+
active --> [*]: DELETE (revoca + eliminazione)
|
|
178
|
+
needs_reauth --> [*]: DELETE
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
Un errore temporaneo del provider (rete, 5xx) non cambia lo stato: la richiesta risponde 503 e quella successiva riprova.
|
|
182
|
+
|
|
183
|
+
## 8. API
|
|
184
|
+
|
|
185
|
+
Base: `/:project_id/mcp/oauth` (header `Authorization: JWT …`). Tutte le route rispondono 503 `not_configured` se la funzionalità non è configurata.
|
|
186
|
+
|
|
187
|
+
| Metodo e path | Chi | Scopo |
|
|
188
|
+
|---|---|---|
|
|
189
|
+
| `POST /authorize` | admin | Avvia il flusso. Body `{ mode, server_url, name?, scopes?, manual?, return_url? }` → `{ authorization_url, connection_id }` |
|
|
190
|
+
| `GET /connections` | admin | Elenco delle connessioni (senza segreti) |
|
|
191
|
+
| `GET /connections/:id` | admin | Una connessione: `status`, `expires_at`, `last_error`, `granted_scopes`, … |
|
|
192
|
+
| `POST /connections/:id/refresh` | admin | Forza un refresh |
|
|
193
|
+
| `DELETE /connections/:id` | admin | Revoca sul provider, elimina, toglie `oauth` dall'integrazione |
|
|
194
|
+
| `GET /connections/:id/token` | bot, subscription | `{ access_token, token_type, expires_at }` |
|
|
195
|
+
|
|
196
|
+
Altre route:
|
|
197
|
+
|
|
198
|
+
| Metodo e path | Scopo |
|
|
199
|
+
|---|---|
|
|
200
|
+
| `GET /oauth2/mcp/callback` | Redirect del provider (pubblica, protetta dallo `state` monouso) |
|
|
201
|
+
| `POST /webhook/mcp-oauth/refresh` | Scheduler. Header `x-auth-token`. Body `{ within_seconds }` (60..86400, default 900) oppure `{ connection_id }` |
|
|
202
|
+
| `POST /:project_id/mcp/connect`, `/tools`, `/servers` | Accettano `oauth: { connection_id }` per i server custom |
|
|
203
|
+
|
|
204
|
+
Errori principali: 400 body non valido, discovery non supportata, connessione usata per un altro URL; 403 admin sull'endpoint del token; 404 connessione inesistente o di un altro progetto; 409 `needs_reauth`; 502/503 provider non raggiungibile.
|
|
205
|
+
|
|
206
|
+
## 9. Configurazione
|
|
207
|
+
|
|
208
|
+
| Variabile | Obbligatoria | Scopo |
|
|
209
|
+
|---|---|---|
|
|
210
|
+
| `MCP_OAUTH_ENCRYPTION_KEY` | sì | 32 byte in base64 (`openssl rand -base64 32`). Stesso valore su tutte le repliche e stabile nel tempo: cambiarla rende illeggibili i token salvati |
|
|
211
|
+
| `MCP_OAUTH_REDIRECT_BASE_URL` | sì (in alternativa `API_URL`) | URL pubblico delle API, es. `https://stage.eks.tiledesk.com/api`. Redirect URI = `<base>/oauth2/mcp/callback` |
|
|
212
|
+
| `MCP_OAUTH_GOOGLE_CLIENT_ID`, `MCP_OAUTH_GOOGLE_CLIENT_SECRET` | per `google` | Client OAuth Google di tipo "Web application" |
|
|
213
|
+
| `MCP_OAUTH_REFRESH_TOKEN` | per lo scheduler | Segreto condiviso del webhook di refresh (stesso valore sul worker dello scheduler) |
|
|
214
|
+
| `MCP_OAUTH_RETURN_ORIGINS` | solo con `return_url` | Origin ammessi per il redirect dopo la callback. Il flusso con popup della dashboard non ne ha bisogno |
|
|
215
|
+
| `MCP_OAUTH_ALLOW_INSECURE_URLS` | mai in produzione | `true` ammette `http://` e indirizzi privati: solo sviluppo locale |
|
|
216
|
+
|
|
217
|
+
### Configurazione Google
|
|
218
|
+
|
|
219
|
+
1. Progetto Google Cloud: abilita l'API del servizio e il relativo servizio MCP (es. `calendar-json.googleapis.com` e `calendarmcp.googleapis.com`; per i server Google Cloud `gcloud beta services mcp enable <servizio>`).
|
|
220
|
+
2. Google Auth Platform: schermata di consenso (in "Testing" aggiungi i test user), scope in Data Access.
|
|
221
|
+
3. Client di tipo **Web application**, redirect URI esattamente `<MCP_OAUTH_REDIRECT_BASE_URL>/oauth2/mcp/callback`, opzione **"Use this client for an AI-powered agent"** attiva (richiesta dai server MCP di Google Workspace).
|
|
222
|
+
4. Client ID e secret nelle due variabili d'ambiente, riavvio dei pod.
|
|
223
|
+
|
|
224
|
+
In stato "Testing" i refresh token Google durano 7 giorni. Gli scope sensibili o riservati (Gmail, Drive) richiedono la verifica di Google prima della produzione.
|
|
225
|
+
|
|
226
|
+
## 10. Esempi
|
|
227
|
+
|
|
228
|
+
**Google Calendar**
|
|
229
|
+
|
|
230
|
+
```json
|
|
231
|
+
POST /:project_id/mcp/oauth/authorize
|
|
232
|
+
{
|
|
233
|
+
"mode": "google",
|
|
234
|
+
"server_url": "https://calendarmcp.googleapis.com/mcp/v1",
|
|
235
|
+
"name": "Google Calendar"
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
`scopes` si può omettere per i server MCP Google elencati in `services/mcpOAuthGoogleScopes.js` (Gmail, Drive, Docs, Sheets, Slides, Calendar, Chat, People, Classroom, BigQuery): il server usa gli scope documentati da Google, qui i tre scope in sola lettura di Calendar. Gli scope inviati nel body sostituiscono quelli predefiniti, per esempio `"scopes": ["https://www.googleapis.com/auth/calendar.events"]` per la scrittura. Qualsiasi altro URL Google senza `scopes` risponde 400. Gli stessi scope vanno aggiunti in Google Auth Platform → Data Access.
|
|
240
|
+
|
|
241
|
+
**Server MCP con discovery**
|
|
242
|
+
|
|
243
|
+
```json
|
|
244
|
+
{ "mode": "mcp", "server_url": "https://mcp.example.com/mcp", "name": "Example" }
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
**Provider manuale**
|
|
248
|
+
|
|
249
|
+
```json
|
|
250
|
+
{
|
|
251
|
+
"mode": "manual",
|
|
252
|
+
"server_url": "https://mcp.example.com/mcp",
|
|
253
|
+
"scopes": ["read"],
|
|
254
|
+
"manual": {
|
|
255
|
+
"authorization_endpoint": "https://auth.example.com/authorize",
|
|
256
|
+
"token_endpoint": "https://auth.example.com/token",
|
|
257
|
+
"client_id": "abc",
|
|
258
|
+
"client_secret": "…"
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
Poi, in tutti i casi: apri `authorization_url`, approva e usa il `connection_id` in `/mcp/tools` e `/mcp/servers`. Una collection Postman con queste chiamate è in `postman/import/` (in locale, non ancora committata).
|
|
264
|
+
|
|
265
|
+
## 11. Sicurezza
|
|
266
|
+
|
|
267
|
+
- Authorization code + **PKCE S256** sempre; `state` casuale, monouso, 10 minuti, legato a progetto e utente.
|
|
268
|
+
- Access token, refresh token e client secret **cifrati a riposo** (AES-256-GCM); mai restituiti dalle API di gestione; oscurati nei log.
|
|
269
|
+
- L'integrazione contiene solo `connection_id`: i token non finiscono mai nella cache delle integrazioni né nella dashboard.
|
|
270
|
+
- Il Bearer viene inviato solo all'URL per cui la connessione è stata autorizzata: usare una connessione con un altro URL risponde 400.
|
|
271
|
+
- Controllo degli URL in uscita: solo https, niente indirizzi privati, loopback o link-local, niente redirect, timeout e limiti sulla dimensione delle risposte.
|
|
272
|
+
- `return_url` ammesso solo verso gli origin in `MCP_OAUTH_RETURN_ORIGINS`.
|
|
273
|
+
- Webhook dello scheduler protetto da un token condiviso confrontato in tempo costante.
|
|
274
|
+
|
|
275
|
+
## 12. Test
|
|
276
|
+
|
|
277
|
+
- Automatici: test mocha `test/mcpOAuthUtils`, `mcpOAuthDiscovery`, `mcpOAuthService`, `mcpOAuthRoute`, `mcpServiceOAuth` (provider e server MCP simulati con nock, Mongo e Redis reali).
|
|
278
|
+
- End to end, in locale: [modelcontextprotocol/example-remote-server](https://github.com/modelcontextprotocol/example-remote-server) (`npm run dev:internal`, porta 3232) con `MCP_OAUTH_ALLOW_INSECURE_URLS=true`. Su un URL pubblico va avviato con `BASE_URI=<URL pubblico>`, altrimenti i suoi metadata puntano a `localhost`.
|
|
279
|
+
- Stage: modalità `mcp` con il server di riferimento dietro un tunnel pubblico, modalità `google` con un client Google Cloud.
|