-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoJobMCP.yaml
More file actions
594 lines (562 loc) · 20.5 KB
/
oJobMCP.yaml
File metadata and controls
594 lines (562 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
# Copyright 2025 Nuno Aguiar
# MCP Server Job
# This job starts a MCP server that listens for requests and executes jobs based on the requests.
include:
- oJobHTTPd.yaml
jobs:
# -------------------------
- name : HTTP MCP Server
typeArgs:
noLog : false
shortcut:
name : httpdMCP
keyArg: port
args :
description: description
uri : uri
usestream : usestream
debug : debug
tplDesc : tplDesc
toolPrefix : toolPrefix
fnsMeta : fnsMeta
fns : fns
help :
text: Starts a MCP server to handle requests with execution of jobs.
expects:
- name: port
desc: (Number) The port to listen on.
- name: uri
desc: (String) The URI to handle requests. Default is "/mcp".
- name: usestream
desc: (Boolean) If true, returns responses as HTTP SSE stream events.
- name: debug
desc: (Boolean) If true, debug messages will be logged.
- name: tplDesc
desc: (Boolean) If true, all tool description fields in fnsMeta are evaluated as handlebars templates with the current oJob args.
- name: toolPrefix
desc: (String) If defined, prefixes exposed MCP tool names without changing fns/fnsMeta key mapping.
- name: fnsMeta
desc: (Map) Metadata for the functions available in the MCP server.
- name: fns
desc: (Map) Functions to be executed when called from the MCP server.
check :
in:
description: isMap.default(__)
port : isNumber
uri : isString.default("/mcp")
usestream : toBoolean.isBoolean.default(false)
debug : toBoolean.isBoolean.default(false)
tplDesc : toBoolean.isBoolean.default(false)
toolPrefix : isString.default("")
fnsMeta : isMap.default({})
fns : isMap.default({})
deps :
- HTTP Start Server
exec : | #js
var _applyTemplate = (meta, allStrings) => {
if (!args.tplDesc) return meta
var _walk = obj => {
if (isString(obj) && allStrings) return $t(obj, args)
if (isArray(obj)) return obj.map(_walk)
if (isMap(obj)) {
Object.keys(obj).forEach(k => {
if (isString(obj[k]) && (allStrings || k == "description")) {
obj[k] = $t(obj[k], args)
} else {
obj[k] = _walk(obj[k])
}
})
}
return obj
}
return _walk(meta)
}
// Ensures default server info and capabilities
args.description = merge({
protocolVersion: "2024-11-05",
serverInfo: {
name: "OpenAF",
title: "OpenAF MCP server",
version: "1.0.0"
},
capabilities: {
prompts: {
listChanged: true
},
tools: {
listChanged: true
}
}
}, args.description)
args.description = _applyTemplate(clone(args.description), true)
fns = {}
var _applyTemplateToDescriptions = meta => _applyTemplate(meta, false)
var _prefixToolName = n => (isString(args.toolPrefix) && args.toolPrefix.length > 0 ? args.toolPrefix + n : n)
var _resolveToolName = n => {
if (isString(args.toolPrefix) && args.toolPrefix.length > 0 && isString(n) && n.startsWith(args.toolPrefix)) {
return n.substring(args.toolPrefix.length)
}
return n
}
var _toToolMeta = f => {
var _meta
if (isDef(args.fnsMeta[f])) {
_meta = _applyTemplateToDescriptions(clone(args.fnsMeta[f]))
} else {
_meta = {
name : f,
description: f,
inputSchema: {}
}
}
if (!isMap(_meta)) _meta = { name: f, description: String(_meta), inputSchema: {} }
_meta.name = _prefixToolName(f)
return _meta
}
if (args.usestream) {
fns[args.uri] = req => {
try {
var _rpcFns = {
initialize : params => {
if (args.debug) log(`initialize -- ${af.toCSLON(params)}`)
return args.description
},
"notifications/cancelled" : params => ({}),
"notifications/initialized": params => ({}),
"ping" : params => {
if (args.debug) log(`ping -- ${af.toCSLON(params)}`)
return {}
},
"tools/call" : params => {
if (args.debug) log(`tools/call -- ${af.toCSLON(params)}`)
var _res
var _toolName = _resolveToolName(params.name)
if (isDef(args.fns[_toolName])) {
try {
if (isString(args.fns[_toolName])) {
_res = $job(args.fns[_toolName], merge({ _httprequest: req }, params.arguments || params.input || {}))
if (isMap(_res)) {
delete _res.objId
delete _res.execid
// Check for _err and treat it as an error
if (isDef(_res._err)) {
var errMsg = _res._err
delete _res._err
logErr(`Error executing tool '${params.name}': ${errMsg}`)
_res = {
content: [{
type: "text",
text: String(errMsg)
}],
isError: true
}
}
}
} else {
throw "Function not found: " + _toolName
}
} catch(e) {
logErr(`Error executing tool '${params.name}': ${e.message}`)
_res = {
content: [{
type: "text",
text: `Error executing tool '${params.name}': ${e.message}`
}],
isError: true
}
$err(e)
}
} else {
_res = {
content: [{
type: "text",
text: `Error: Unknown tool '${params.name}'`
}],
isError: true
}
}
try {
if (isDef(_res) && _res.isError !== true && isString(_res.text)) {
_res = {
content: [{
type: "text",
text: _res.text
}],
isError: false
}
} else if (isDef(_res) && _res.isError !== true && isUnDef(_res.result)) {
_res = {
content: [{
type: "text",
text: isDef(__flags.MCPSERVER) && __flags.MCPSERVER.answerInTOON ? af.toTOON(_res) : stringify(_res, __, "")
}],
isError: false
}
} else {
if (isDef(_res) && _res.isError !== true) _res = _res.result
}
} catch(eee) { $err(eee) }
if (args.debug) log(`tools/call -- response: ${af.toCSLON(_res)}`)
return _res
},
"tools/list": params => {
if (args.debug) log(`tools/list -- ${af.toCSLON(params)}`)
var _fnsMeta = Object.keys(args.fns).map(f => _toToolMeta(f))
return {
tools: _fnsMeta
}
},
"prompts/list": params => ({})
}
// Process the JSON-RPC request
var _rpcRes = ow.server.httpd.replyJSONRPC(global.__ojobHttp[args.port], req, _rpcFns, log, m => { if (args.debug) print(ansiColor("BG(230),BLACK", m)) })
// Parse request to check if it's a notification
var body = (isDef(req.files) && isDef(req.files.postData)) ? req.files.postData : __
if (isUnDef(body) && isDef(req.data)) body = req.data
var reqObj
try {
reqObj = jsonParse(body)
} catch(e) {
return { data: "Invalid JSON", mimetype: "text/plain", status: 400, header: {} }
}
// For notifications (no id field), return 204 No Content immediately
if (isUnDef(reqObj.id)) {
if (args.debug) log("Notification received: " + reqObj.method)
return { data: "", mimetype: "text/plain", status: 204, header: {} }
}
// For requests with id, return SSE stream
var pis = new java.io.PipedInputStream()
var pos = new java.io.PipedOutputStream(pis)
$doV(function() {
try {
var _payload = _rpcRes
if (isMap(_rpcRes) && isDef(_rpcRes.data)) _payload = _rpcRes.data
if (isString(_payload)) {
try { _payload = jsonParse(_payload) } catch(__e) {}
}
if (isDef(_payload) && _payload !== "") {
var msg = "event: message\n"
msg += "data: " + (isDef(__flags.MCPSERVER) && __flags.MCPSERVER.answerInTOON ? af.toTOON(_payload) : JSON.stringify(_payload)) + "\n\n"
pos.write(af.fromString2Bytes(msg))
pos.flush()
}
} catch(e) {
try {
var errMsg = "event: error\n"
errMsg += "data: " + JSON.stringify({ message: String(e) }) + "\n\n"
pos.write(af.fromString2Bytes(errMsg))
pos.flush()
} catch(e2) {
logErr("MCP stream error: " + String(e2))
}
} finally {
try { pos.close() } catch(e) {}
}
})
return {
status : 200,
mimetype: "text/event-stream",
stream : pis,
header : {
"Cache-Control" : "no-cache, no-transform",
"Connection" : "keep-alive",
"Content-Encoding" : "identity",
"X-Accel-Buffering": "no"
}
}
} catch(e) {
return { data: String(e), mimetype: "text/plain", status: 500, header: {} }
}
}
} else {
fns[args.uri] = req => {
var _rpcFns = {
initialize : params => {
if (args.debug) log(`initialize -- ${af.toCSLON(params)}`)
return args.description
},
"notifications/cancelled" : params => ({}),
"notifications/initialized": params => ({}),
"ping" : params => {
if (args.debug) log(`ping -- ${af.toCSLON(params)}`)
return {}
},
"tools/call" : params => {
if (args.debug) log(`tools/call -- ${af.toCSLON(params)}`)
var _res
var _toolName = _resolveToolName(params.name)
if (isDef(args.fns[_toolName])) {
try {
if (isString(args.fns[_toolName])) {
_res = $job(args.fns[_toolName], merge({ _httprequest: req }, params.arguments || params.input || {}))
if (isMap(_res)) {
delete _res.objId
delete _res.execid
// Check for _err and treat it as an error
if (isDef(_res._err)) {
var errMsg = _res._err
delete _res._err
logErr(`Error executing tool '${params.name}': ${errMsg}`)
_res = {
content: [{
type: "text",
text: String(errMsg)
}],
isError: true
}
}
}
} else {
throw "Function not found: " + _toolName
}
} catch(e) {
logErr(`Error executing tool '${params.name}': ${e.message}`)
_res = {
content: [{
type: "text",
text: `Error executing tool '${params.name}': ${e.message}`
}],
isError: true
}
$err(e)
}
} else {
_res = {
content: [{
type: "text",
text: `Error: Unknown tool '${params.name}'`
}],
isError: true
}
}
try {
if (isDef(_res) && _res.isError !== true && isString(_res.text)) {
_res = {
content: [{
type: "text",
text: _res.text
}],
isError: false
}
} else if (isDef(_res) && _res.isError !== true && isUnDef(_res.result)) {
_res = {
content: [{
type: "text",
text: (isDef(__flags.MCPSERVER) && __flags.MCPSERVER.answerInTOON ? af.toTOON(_res) : stringify(_res, __, ""))
}],
isError: false
}
} else {
if (isDef(_res) && _res.isError !== true) _res = _res.result
}
} catch(eee) { $err(eee) }
if (args.debug) log(`tools/call -- response: ${af.toCSLON(_res)}`)
return _res
},
"tools/list": params => {
if (args.debug) log(`tools/list -- ${af.toCSLON(params)}`)
var _fnsMeta = Object.keys(args.fns).map(f => _toToolMeta(f))
return {
tools: _fnsMeta
}
},
"prompts/list": params => ({})
}
return ow.server.httpd.replyJSONRPC(global.__ojobHttp[args.port], req, _rpcFns, log, m => { if (args.debug) print(ansiColor("BG(230),BLACK", m)) })
}
}
// Add handler for .well-known endpoint (optional OAuth discovery)
/*fns[args.uri + "/.well-known/oauth-authorization-server"] = req => {
return { data: "{}", mimetype: "application/json", status: 404, header: {} }
}*/
ow.server.httpd.route(global.__ojobHttp[args.port], merge(global.__ojobRoutes[args.port], fns))
log("READY [" + args.port + "]")
# --------------------------
- name : STDIO MCP Server
typeArgs:
noLog : false
shortcut:
name : stdioMCP
keyArg: description
args :
debug : debug
tplDesc : tplDesc
toolPrefix : toolPrefix
fnsMeta : fnsMeta
fns : fns
help :
text: Starts a MCP stdio to handle requests with execution of jobs.
expects:
- name: debug
desc: (String) If defined it will create a ndjson file with the provided name.
- name: fnsMeta
desc: (Map) Metadata for the functions available in the MCP server stdio.
- name: tplDesc
desc: (Boolean) If true, all tool description fields in fnsMeta are evaluated as handlebars templates with the current oJob args.
- name: toolPrefix
desc: (String) If defined, prefixes exposed MCP tool names without changing fns/fnsMeta key mapping.
- name: fns
desc: (Map) Functions to be executed when called from the MCP server stdio.
check :
in:
description: isMap.default(__)
debug : isString.default(__)
tplDesc : toBoolean.isBoolean.default(false)
toolPrefix : isString.default("")
fnsMeta : isMap.default({})
fns : isMap.default({})
exec : | #js
var _applyTemplate = (meta, allStrings) => {
if (!args.tplDesc) return meta
var _walk = obj => {
if (isString(obj) && allStrings) return $t(obj, args)
if (isArray(obj)) return obj.map(_walk)
if (isMap(obj)) {
Object.keys(obj).forEach(k => {
if (isString(obj[k]) && (allStrings || k == "description")) {
obj[k] = $t(obj[k], args)
} else {
obj[k] = _walk(obj[k])
}
})
}
return obj
}
return _walk(meta)
}
// Ensures default server info and capabilities
args.description = merge({
protocolVersion: "2024-11-05",
serverInfo: {
name: "OpenAF",
title: "OpenAF server",
version: "1.0.0"
},
capabilities: {
prompts: {
listChanged: true
},
tools: {
listChanged: true
}
}
}, args.description)
args.description = _applyTemplate(clone(args.description), true)
var fs = {}
var _applyTemplateToDescriptions = meta => _applyTemplate(meta, false)
var _prefixToolName = n => (isString(args.toolPrefix) && args.toolPrefix.length > 0 ? args.toolPrefix + n : n)
var _resolveToolName = n => {
if (isString(args.toolPrefix) && args.toolPrefix.length > 0 && isString(n) && n.startsWith(args.toolPrefix)) {
return n.substring(args.toolPrefix.length)
}
return n
}
var _toToolMeta = f => {
var _meta
if (isDef(args.fnsMeta[f])) {
_meta = _applyTemplateToDescriptions(clone(args.fnsMeta[f]))
} else {
_meta = {
name : f,
description: f,
inputSchema: {}
}
}
if (!isMap(_meta)) _meta = { name: f, description: String(_meta), inputSchema: {} }
_meta.name = _prefixToolName(f)
return _meta
}
Object.keys(args.fns).forEach(f => {
var _toolName = _prefixToolName(f)
fs[_toolName] = function(params) {
var _jobName = _resolveToolName(_toolName)
var _r = $job(args.fns[_jobName], params)
if (isMap(_r)) {
delete _r.objId
delete _r.execid
// Check for _err and treat it as an error
if (isDef(_r._err)) {
var errMsg = _r._err
delete _r._err
throw String(errMsg)
}
}
return _r
}
})
ow.server.mcpStdio(args.description, Object.keys(args.fns).map(f => _toToolMeta(f)),
fs,
(type, msg) => {
if (args.debug) {
io.writeLineNDJSON(args.debug, { type: type, msg: msg })
}
})
# - name: ping
# exec: | #js
# args.text = "PONG!"
# - name: echo
# exec: | #js
# args.text = args.text
# - name: specialSum
# exec: | #js
# args.text = Number(args.a) + Number(args.b) * 2
# ojob:
# #logToConsole: false
# daemon : true
# todo:
# #- (stdioMCP ): {}
# # ((debug )): /Applications/OpenAF/oJob-common/log.ndjson
# - (httpdStart): 17878
# - (httpdMCP ): 17878
# ((debug )): true
# ((uri )): "/mcp"
# ((fnsMeta)):
# ping:
# name : ping
# description: Pings the server
# inputSchema:
# type: object
# properties:
# text:
# type: string
# description: Text to return
# required: ["text"]
# annotations:
# title : Ping
# readOnlyHint: false
# idempotentHint: true
# echo:
# name : echo
# description: Echoes the input
# title : echo
# inputSchema:
# type: object
# properties:
# text:
# type: string
# description: Text to echo
# required: ["text"]
# annotations:
# title : Echo
# readOnlyHint: false
# idempotentHint: true
# specialSum:
# name : specialSum
# description: Performs a special sum
# inputSchema:
# type: object
# properties:
# a:
# type: number
# description: the a number of the sum
# b:
# type: number
# description: the b number of the sum
# required: ["a","b"]
# annotations:
# title: specialSum
# readOnlyHint: false
# ((fns )):
# ping: ping
# echo: echo
# specialSum: specialSum