@tiledesk/tiledesk-server 3.3.4 → 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 +20 -1
- 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 +2 -2
- 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
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* POST /:projectid/executions/refire — "start new" of an agent execution (traceability Phase 3).
|
|
3
|
+
*
|
|
4
|
+
* Called by tiledesk-executions with the user's own Authorization header after it audited the start new:
|
|
5
|
+
* { chatbot_id, trigger: { type, source_id, start_point_id }, payload, retry_of }
|
|
6
|
+
* It starts a new run of the same unattended trigger with the user-confirmed `payload` (never re-read
|
|
7
|
+
* from the stored mapping), carrying `retry_of` so tybot links the new execution to the old one.
|
|
8
|
+
* Replies `{ success: true, request_id }`.
|
|
9
|
+
*
|
|
10
|
+
* Mounted only when EXECUTIONS_AMQP_URL is set (mountIfEnabled). Needs `executions_control`: owner/admin
|
|
11
|
+
* by role hierarchy, a custom role only with that permission; agent/supervisor get 403.
|
|
12
|
+
* Bodies up to the global JSON_BODY_LIMIT (default 500KB) are accepted, enough for the ~300 KB refire.
|
|
13
|
+
*/
|
|
14
|
+
const express = require('express');
|
|
15
|
+
const passport = require('passport');
|
|
16
|
+
const winston = require('../config/winston');
|
|
17
|
+
const validtoken = require('../middleware/valid-token');
|
|
18
|
+
const roleChecker = require('../middleware/has-role');
|
|
19
|
+
const { Webhook } = require('../models/webhook');
|
|
20
|
+
const webhookService = require('../services/webhookService');
|
|
21
|
+
const webhookSettingsValidator = require('../services/webhookSettingsValidator');
|
|
22
|
+
const webhookEvent = require('../event/webhookEvent');
|
|
23
|
+
const webhookRoute = require('./webhook');
|
|
24
|
+
const ObjectId = require('mongoose').Types.ObjectId;
|
|
25
|
+
|
|
26
|
+
const PERMISSION = 'executions_control';
|
|
27
|
+
// Keys the server and tybot add to an automation payload on its way to /block (the stored payload carries them):
|
|
28
|
+
// never taken from the user's confirmed input. webhook_http_method / webhook_query_params describe the call: kept.
|
|
29
|
+
const SERVER_KEYS = ['request_id', 'preloaded_request_id', 'token', 'async', 'draft'];
|
|
30
|
+
const TRIGGER_TYPES = ['scheduled', 'webhook', 'automation'];
|
|
31
|
+
|
|
32
|
+
const router = express.Router({ mergeParams: true });
|
|
33
|
+
|
|
34
|
+
function isObject(v) {
|
|
35
|
+
return v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function findProjectWebhook(id_project, webhook_id) {
|
|
39
|
+
if (!webhook_id) {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
return Webhook.findOne({ id_project: String(id_project), webhook_id: String(webhook_id) });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function refireAutomation(req, res, webhook, payload, retry_of) {
|
|
46
|
+
if (!(await webhookRoute.checkEnabledAndRateLimit(req, res, webhook))) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
// Same body the public automation route builds; tybot's /block lifts the top-level retry_of out of it.
|
|
50
|
+
const body = Object.assign({}, payload, { retry_of: retry_of });
|
|
51
|
+
SERVER_KEYS.forEach(function (k) { delete body[k]; });
|
|
52
|
+
body.request_id = "automation-request-" + webhook.id_project + "-" + new ObjectId() + "-" + webhook.webhook_id;
|
|
53
|
+
try {
|
|
54
|
+
// forceAsync: the reply comes once tybot took the run, never after the flow (a sync webhook could outlast the
|
|
55
|
+
// caller's timeout, and the user's retry would start a second run)
|
|
56
|
+
await webhookService.run(webhook, body, undefined, undefined, { forceAsync: true });
|
|
57
|
+
} catch (err) {
|
|
58
|
+
winston.error("(executions-refire) automation run failed for webhook " + webhook.webhook_id, err);
|
|
59
|
+
const status = (err && err.status) || 500;
|
|
60
|
+
return res.status(status).send({ success: false, error: "Error running the automation" });
|
|
61
|
+
}
|
|
62
|
+
webhookEvent.emit("webhook.triggered", { webhook: webhook, payload: body });
|
|
63
|
+
return res.status(202).send({ success: true, request_id: body.preloaded_request_id });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
router.post('/refire', async (req, res) => {
|
|
67
|
+
const id_project = req.params.projectid;
|
|
68
|
+
const b = req.body || {};
|
|
69
|
+
const trigger = isObject(b.trigger) ? b.trigger : {};
|
|
70
|
+
const type = trigger.type;
|
|
71
|
+
const retry_of = b.retry_of;
|
|
72
|
+
const payload = isObject(b.payload) ? b.payload : {};
|
|
73
|
+
|
|
74
|
+
if (!b.chatbot_id || typeof b.chatbot_id !== 'string') {
|
|
75
|
+
return res.status(400).send({ success: false, error: 'chatbot_id is required' });
|
|
76
|
+
}
|
|
77
|
+
if (TRIGGER_TYPES.indexOf(type) < 0) {
|
|
78
|
+
return res.status(400).send({ success: false, error: 'unknown_trigger_type' });
|
|
79
|
+
}
|
|
80
|
+
if (retry_of !== undefined && retry_of !== null && typeof retry_of !== 'string') {
|
|
81
|
+
return res.status(400).send({ success: false, error: 'retry_of must be a string' });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
let chatbot;
|
|
85
|
+
try {
|
|
86
|
+
chatbot = await webhookSettingsValidator.findChatbot(String(id_project), b.chatbot_id);
|
|
87
|
+
} catch (err) {
|
|
88
|
+
winston.error("(executions-refire) error finding chatbot " + b.chatbot_id, err);
|
|
89
|
+
return res.status(500).send({ success: false, error: 'Error finding chatbot' });
|
|
90
|
+
}
|
|
91
|
+
if (!chatbot) {
|
|
92
|
+
return res.status(404).send({ success: false, error: 'chatbot_not_found' });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const extraAttributes = retry_of ? { retry_of: retry_of } : {};
|
|
96
|
+
|
|
97
|
+
if (type === 'scheduled') {
|
|
98
|
+
return webhookRoute.startScheduledRun(req, res, {
|
|
99
|
+
id_project: String(id_project),
|
|
100
|
+
chatbot_id: b.chatbot_id,
|
|
101
|
+
payload: payload,
|
|
102
|
+
extraAttributes: extraAttributes
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
let webhook;
|
|
107
|
+
try {
|
|
108
|
+
webhook = await findProjectWebhook(id_project, trigger.source_id);
|
|
109
|
+
} catch (err) {
|
|
110
|
+
winston.error("(executions-refire) error finding webhook " + trigger.source_id, err);
|
|
111
|
+
return res.status(500).send({ success: false, error: 'Error finding webhook' });
|
|
112
|
+
}
|
|
113
|
+
if (!webhook || String(webhook.chatbot_id) !== String(b.chatbot_id)) {
|
|
114
|
+
return res.status(404).send({ success: false, error: 'webhook_not_found' });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// The run kind follows the webhook's current mode; a refire of the other kind would start the wrong path.
|
|
118
|
+
const conversationMode = webhook.mode === webhookSettingsValidator.CONVERSATION_MODE;
|
|
119
|
+
if ((type === 'webhook') !== conversationMode) {
|
|
120
|
+
return res.status(409).send({ success: false, error: 'trigger_mismatch' });
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (type === 'webhook') {
|
|
124
|
+
if (!(await webhookRoute.checkEnabledAndRateLimit(req, res, webhook))) {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
return webhookRoute.startWebhookConversation(res, webhook, payload, { dev: false, extraAttributes: extraAttributes });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return refireAutomation(req, res, webhook, payload, retry_of);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
// The off switch: the route exists only when EXECUTIONS_AMQP_URL is set (read when mounting).
|
|
134
|
+
function mountIfEnabled(app) {
|
|
135
|
+
if (!process.env.EXECUTIONS_AMQP_URL) {
|
|
136
|
+
winston.info("executions refire route disabled: EXECUTIONS_AMQP_URL not set");
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
app.use('/:projectid/executions', [
|
|
140
|
+
passport.authenticate(['basic', 'jwt'], { session: false }),
|
|
141
|
+
validtoken,
|
|
142
|
+
roleChecker.hasRoleOrTypes('admin', undefined, PERMISSION)
|
|
143
|
+
], router);
|
|
144
|
+
return true;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
module.exports = router;
|
|
148
|
+
module.exports.mountIfEnabled = mountIfEnabled;
|
package/routes/mcp.js
CHANGED
|
@@ -2,6 +2,9 @@ let express = require('express');
|
|
|
2
2
|
let router = express.Router();
|
|
3
3
|
let winston = require('../config/winston');
|
|
4
4
|
const mcpService = require('../services/mcpService');
|
|
5
|
+
const mcpOAuth = require('./mcpOAuth');
|
|
6
|
+
|
|
7
|
+
router.use('/oauth', mcpOAuth);
|
|
5
8
|
|
|
6
9
|
|
|
7
10
|
/**
|
|
@@ -39,7 +42,7 @@ router.post('/native/:nativeId/connect', async (req, res) => {
|
|
|
39
42
|
});
|
|
40
43
|
} catch (error) {
|
|
41
44
|
winston.error('Error connecting to native MCP server:', error);
|
|
42
|
-
res.status(error.statusCode || 500).send({
|
|
45
|
+
res.status(error.statusCode || error.status || 500).send({
|
|
43
46
|
success: false,
|
|
44
47
|
error: error.message || 'Error connecting to native MCP server'
|
|
45
48
|
});
|
|
@@ -61,7 +64,7 @@ router.post('/native/:nativeId/tools', async (req, res) => {
|
|
|
61
64
|
res.status(200).send(tools);
|
|
62
65
|
} catch (error) {
|
|
63
66
|
winston.error('Error getting tools from native MCP server:', error);
|
|
64
|
-
res.status(error.statusCode || 500).send({
|
|
67
|
+
res.status(error.statusCode || error.status || 500).send({
|
|
65
68
|
success: false,
|
|
66
69
|
error: error.message || 'Error getting tools from native MCP server'
|
|
67
70
|
});
|
|
@@ -72,7 +75,7 @@ router.post('/native/:nativeId/tools', async (req, res) => {
|
|
|
72
75
|
* POST /mcp/servers
|
|
73
76
|
* Adds or updates an MCP server in the project mcp integration
|
|
74
77
|
* Body (native): { type: 'native', nativeId, tools?, selectedTools? }
|
|
75
|
-
* Body (custom): { type: 'custom', name, url, transport?, customHeaders?, tools?, selectedTools?, auth
|
|
78
|
+
* Body (custom): { type: 'custom', name, url, transport?, customHeaders?, tools?, selectedTools?, auth?, oauth?: { connection_id } }
|
|
76
79
|
*/
|
|
77
80
|
router.post('/servers', async (req, res) => {
|
|
78
81
|
try {
|
|
@@ -86,7 +89,7 @@ router.post('/servers', async (req, res) => {
|
|
|
86
89
|
});
|
|
87
90
|
} catch (error) {
|
|
88
91
|
winston.error('Error saving MCP server in integration:', error);
|
|
89
|
-
res.status(error.statusCode || 500).send({
|
|
92
|
+
res.status(error.statusCode || error.status || 500).send({
|
|
90
93
|
success: false,
|
|
91
94
|
error: error.message || 'Error saving MCP server in integration'
|
|
92
95
|
});
|
|
@@ -99,7 +102,7 @@ router.post('/servers', async (req, res) => {
|
|
|
99
102
|
* Body: {
|
|
100
103
|
* url: string,
|
|
101
104
|
* customHeaders?: [{ key: string, value: string }],
|
|
102
|
-
* oauth?:
|
|
105
|
+
* oauth?: { connection_id: string } (MCP OAuth connection of the project, see /mcp/oauth),
|
|
103
106
|
* auth?: object (legacy, optional)
|
|
104
107
|
* }
|
|
105
108
|
*/
|
|
@@ -124,7 +127,7 @@ router.post('/connect', async (req, res) => {
|
|
|
124
127
|
});
|
|
125
128
|
} catch (error) {
|
|
126
129
|
winston.error(`Error connecting to MCP server:`, error);
|
|
127
|
-
res.status(500).send({ success: false, error: error.message || 'Error connecting to MCP server' });
|
|
130
|
+
res.status(error.statusCode || error.status || 500).send({ success: false, error: error.message || 'Error connecting to MCP server' });
|
|
128
131
|
}
|
|
129
132
|
});
|
|
130
133
|
|
|
@@ -134,7 +137,7 @@ router.post('/connect', async (req, res) => {
|
|
|
134
137
|
* Body: {
|
|
135
138
|
* url: string,
|
|
136
139
|
* customHeaders?: [{ key: string, value: string }],
|
|
137
|
-
* oauth?:
|
|
140
|
+
* oauth?: { connection_id: string } (MCP OAuth connection of the project, see /mcp/oauth),
|
|
138
141
|
* auth?: object (legacy, optional)
|
|
139
142
|
* }
|
|
140
143
|
*/
|
|
@@ -157,7 +160,7 @@ router.post('/tools', async (req, res) => {
|
|
|
157
160
|
res.status(200).send(tools);
|
|
158
161
|
} catch (error) {
|
|
159
162
|
winston.error(`Error getting tools from MCP server:`, error);
|
|
160
|
-
res.status(500).send({ success: false, error: error.message || 'Error getting tools from MCP server' });
|
|
163
|
+
res.status(error.statusCode || error.status || 500).send({ success: false, error: error.message || 'Error getting tools from MCP server' });
|
|
161
164
|
}
|
|
162
165
|
});
|
|
163
166
|
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
let express = require('express');
|
|
2
|
+
let router = express.Router();
|
|
3
|
+
let winston = require('../config/winston');
|
|
4
|
+
const roleChecker = require('../middleware/has-role');
|
|
5
|
+
const Faq_kb = require('../models/faq_kb');
|
|
6
|
+
const Subscription = require('../models/subscription');
|
|
7
|
+
const Integration = require('../models/integrations');
|
|
8
|
+
const McpOAuthConnection = require('../models/mcpOAuthConnection');
|
|
9
|
+
const integrationEvent = require('../event/integrationEvent');
|
|
10
|
+
const mcpOAuthService = require('../services/mcpOAuthService');
|
|
11
|
+
|
|
12
|
+
function sendError(res, error, message) {
|
|
13
|
+
const status = error.status || 500;
|
|
14
|
+
if (status >= 500) {
|
|
15
|
+
winston.error(message + ': ', error);
|
|
16
|
+
} else {
|
|
17
|
+
winston.debug(message + ': ' + error.message);
|
|
18
|
+
}
|
|
19
|
+
res.status(status).send({
|
|
20
|
+
success: false,
|
|
21
|
+
error: status === 500 ? message : error.message,
|
|
22
|
+
code: error.code
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Tokens are served to chatbots and subscriptions of the project only, never to dashboard users.
|
|
27
|
+
function botOrSubscriptionOnly(req, res, next) {
|
|
28
|
+
const user = req.user;
|
|
29
|
+
const isMachine = user instanceof Faq_kb || user instanceof Subscription;
|
|
30
|
+
if (!isMachine || !roleChecker.belongsToProject(user, req.projectid)) {
|
|
31
|
+
return res.status(403).send({ success: false, error: 'Only chatbots of the project can read MCP OAuth tokens' });
|
|
32
|
+
}
|
|
33
|
+
next();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Removes the reference to a deleted connection from the servers of the project mcp integration. */
|
|
37
|
+
async function detachConnection(id_project, connection_id) {
|
|
38
|
+
const integration = await Integration.findOne({ id_project: id_project, name: 'mcp' });
|
|
39
|
+
const servers = integration && Array.isArray(integration.value && integration.value.servers) ? integration.value.servers : [];
|
|
40
|
+
let detached = 0;
|
|
41
|
+
const updatedServers = servers.map((server) => {
|
|
42
|
+
if (server && server.oauth && String(server.oauth.connection_id) === String(connection_id)) {
|
|
43
|
+
detached++;
|
|
44
|
+
const { oauth, ...rest } = server;
|
|
45
|
+
return rest;
|
|
46
|
+
}
|
|
47
|
+
return server;
|
|
48
|
+
});
|
|
49
|
+
if (detached === 0) {
|
|
50
|
+
return 0;
|
|
51
|
+
}
|
|
52
|
+
integration.value = { ...integration.value, servers: updatedServers };
|
|
53
|
+
integration.markModified('value');
|
|
54
|
+
await integration.save();
|
|
55
|
+
const integrations = await Integration.find({ id_project: id_project });
|
|
56
|
+
integrationEvent.emit('integration.update', integrations, id_project);
|
|
57
|
+
return detached;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
router.use((req, res, next) => {
|
|
61
|
+
if (!mcpOAuthService.isConfigured()) {
|
|
62
|
+
return res.status(503).send({ success: false, error: 'MCP OAuth is not available on this installation', code: 'not_configured' });
|
|
63
|
+
}
|
|
64
|
+
next();
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* POST /mcp/oauth/authorize
|
|
69
|
+
* Body: { server_url, mode: 'mcp'|'google'|'manual', name?, scopes?, return_url?, manual? }
|
|
70
|
+
* Returns the URL to open in the browser to authorize the connection.
|
|
71
|
+
*/
|
|
72
|
+
router.post('/authorize', roleChecker.hasRole('admin'), async (req, res) => {
|
|
73
|
+
try {
|
|
74
|
+
const result = await mcpOAuthService.startAuthorization(req.projectid, req.user._id, req.body);
|
|
75
|
+
res.status(200).send({ success: true, ...result });
|
|
76
|
+
} catch (error) {
|
|
77
|
+
sendError(res, error, 'Error starting MCP OAuth authorization');
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
router.get('/connections', roleChecker.hasRole('admin'), async (req, res) => {
|
|
82
|
+
try {
|
|
83
|
+
const connections = await mcpOAuthService.listConnections(req.projectid);
|
|
84
|
+
res.status(200).send(connections.map((connection) => McpOAuthConnection.toPublic(connection)));
|
|
85
|
+
} catch (error) {
|
|
86
|
+
sendError(res, error, 'Error getting MCP OAuth connections');
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
router.get('/connections/:connection_id', roleChecker.hasRole('admin'), async (req, res) => {
|
|
91
|
+
try {
|
|
92
|
+
const connection = await mcpOAuthService.getConnection(req.projectid, req.params.connection_id);
|
|
93
|
+
res.status(200).send(McpOAuthConnection.toPublic(connection));
|
|
94
|
+
} catch (error) {
|
|
95
|
+
sendError(res, error, 'Error getting MCP OAuth connection');
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
router.post('/connections/:connection_id/refresh', roleChecker.hasRole('admin'), async (req, res) => {
|
|
100
|
+
try {
|
|
101
|
+
await mcpOAuthService.getAccessToken(req.projectid, req.params.connection_id, { force: true });
|
|
102
|
+
const connection = await mcpOAuthService.getConnection(req.projectid, req.params.connection_id);
|
|
103
|
+
res.status(200).send(McpOAuthConnection.toPublic(connection));
|
|
104
|
+
} catch (error) {
|
|
105
|
+
sendError(res, error, 'Error refreshing MCP OAuth connection');
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
router.delete('/connections/:connection_id', roleChecker.hasRole('admin'), async (req, res) => {
|
|
110
|
+
try {
|
|
111
|
+
const result = await mcpOAuthService.revokeAndDelete(req.projectid, req.params.connection_id);
|
|
112
|
+
await detachConnection(req.projectid, req.params.connection_id);
|
|
113
|
+
res.status(200).send({ success: true, revoked: result.revoked });
|
|
114
|
+
} catch (error) {
|
|
115
|
+
sendError(res, error, 'Error deleting MCP OAuth connection');
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* GET /mcp/oauth/connections/:connection_id/token
|
|
121
|
+
* Chatbots only: a valid access token, refreshed when it is about to expire.
|
|
122
|
+
*/
|
|
123
|
+
router.get('/connections/:connection_id/token', botOrSubscriptionOnly, async (req, res) => {
|
|
124
|
+
try {
|
|
125
|
+
const token = await mcpOAuthService.getAccessToken(req.projectid, req.params.connection_id);
|
|
126
|
+
res.set('Cache-Control', 'no-store');
|
|
127
|
+
res.status(200).send(token);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
sendError(res, error, 'Error getting MCP OAuth token');
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
module.exports = router;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
let express = require('express');
|
|
2
|
+
let router = express.Router();
|
|
3
|
+
let winston = require('../config/winston');
|
|
4
|
+
const mcpOAuthService = require('../services/mcpOAuthService');
|
|
5
|
+
|
|
6
|
+
function escapeHtml(value) {
|
|
7
|
+
return String(value).replace(/[&<>"']/g, (char) => ({
|
|
8
|
+
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
|
|
9
|
+
}[char]));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function sendPage(res, status, title, message) {
|
|
13
|
+
res.status(status)
|
|
14
|
+
.set('Content-Type', 'text/html; charset=utf-8')
|
|
15
|
+
.send('<!DOCTYPE html><html><head><meta charset="utf-8"><title>' + escapeHtml(title) + '</title></head>' +
|
|
16
|
+
'<body style="font-family:sans-serif;text-align:center;padding-top:15vh">' +
|
|
17
|
+
'<h2>' + escapeHtml(title) + '</h2><p>' + escapeHtml(message) + '</p></body></html>');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Hash-routed dashboards read the query inside the fragment: https://panel/#/route?x=1
|
|
21
|
+
function withParams(returnUrl, params) {
|
|
22
|
+
const url = new URL(returnUrl);
|
|
23
|
+
const query = new URLSearchParams(params).toString();
|
|
24
|
+
if (url.hash) {
|
|
25
|
+
url.hash = url.hash + (url.hash.includes('?') ? '&' : '?') + query;
|
|
26
|
+
} else {
|
|
27
|
+
Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));
|
|
28
|
+
}
|
|
29
|
+
return url.toString();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* GET /oauth2/mcp/callback?code&state
|
|
34
|
+
* Redirect URI registered at the OAuth providers. Authenticated by the single-use state.
|
|
35
|
+
*/
|
|
36
|
+
router.get('/callback', async (req, res) => {
|
|
37
|
+
// The authorization code is in the URL: never leak it through the Referer header.
|
|
38
|
+
res.set('Referrer-Policy', 'no-referrer');
|
|
39
|
+
res.set('Cache-Control', 'no-store');
|
|
40
|
+
|
|
41
|
+
if (!mcpOAuthService.isConfigured()) {
|
|
42
|
+
return sendPage(res, 503, 'Not available', 'MCP OAuth is not available on this installation.');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
let result;
|
|
46
|
+
try {
|
|
47
|
+
result = await mcpOAuthService.completeAuthorization({
|
|
48
|
+
code: req.query.code,
|
|
49
|
+
state: req.query.state,
|
|
50
|
+
error: req.query.error,
|
|
51
|
+
error_description: req.query.error_description
|
|
52
|
+
});
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (error.status === 400 || error.status === 404) {
|
|
55
|
+
return sendPage(res, 400, 'Authorization link expired', 'This authorization link is invalid or has expired. Start the connection again.');
|
|
56
|
+
}
|
|
57
|
+
winston.error('MCP OAuth callback error: ', error);
|
|
58
|
+
return sendPage(res, error.status || 500, 'Authorization failed', 'The connection could not be completed. Try again later.');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const connectionId = result.connection._id.toString();
|
|
62
|
+
if (result.return_url) {
|
|
63
|
+
const params = result.error
|
|
64
|
+
? { mcp_oauth: 'error', error: result.error, connection_id: connectionId }
|
|
65
|
+
: { mcp_oauth: 'success', connection_id: connectionId };
|
|
66
|
+
return res.redirect(302, withParams(result.return_url, params));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (result.error) {
|
|
70
|
+
return sendPage(res, 200, 'Authorization failed', 'The provider answered: ' + result.error + '. You can close this window.');
|
|
71
|
+
}
|
|
72
|
+
return sendPage(res, 200, 'Connected', 'The MCP server is connected. You can close this window.');
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
module.exports = router;
|
package/routes/request.js
CHANGED
|
@@ -574,6 +574,11 @@ router.put('/:requestid/replace', async (req, res) => {
|
|
|
574
574
|
winston.verbose("participants to be set: ", participants);
|
|
575
575
|
|
|
576
576
|
const assignmentOptions = assignmentContextUtil.buildSetParticipantsOptions(req, participants);
|
|
577
|
+
// Subagent calls/returns reuse this route: the reason tells the executions publisher
|
|
578
|
+
// that the bot change is not a replacement of the conversation's bot.
|
|
579
|
+
if (req.body.reason === 'subagent_call' || req.body.reason === 'subagent_return') {
|
|
580
|
+
assignmentOptions.reason = req.body.reason;
|
|
581
|
+
}
|
|
577
582
|
requestService.setParticipantsByRequestId(req.params.requestid, req.projectid, participants, assignmentOptions).then((updatedRequest) => {
|
|
578
583
|
winston.debug("SetParticipant response: ", updatedRequest);
|
|
579
584
|
// Additive: include the resolved canonical (root) bot id for analytics
|