json-object-editor 0.10.444 → 0.10.501

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 CHANGED
@@ -1,5 +1,15 @@
1
1
  ## CHANGELOG
2
2
 
3
+ ### 0.10.500
4
+ 500 - MCP integration (initial)
5
+ - MCP core module with JSON-RPC 2.0 endpoint (/mcp) protected by auth
6
+ - Manifest available at /.well-known/mcp/manifest.json for tool discovery
7
+ - Tools: listSchemas, getSchema, getObject, getObjectsByIds, queryObjects, searchCache, saveObject
8
+ - Tools mapped to real JOE APIs (Schemas, Storage, Cache) with sensitive-field sanitization
9
+ - Read-path prefers Cache for speed; saveObject uses Storage.save (events/history/socket emit)
10
+ - Adopted module init pattern: MCP.init() attaches routes via init.js; removed direct Server.js wiring
11
+ - Basics for local testing (auth + example payloads) to be added to README
12
+
3
13
  ### 0.10.400
4
14
  443 - added npm build support
5
15
  442 - engagements (alpha)
@@ -0,0 +1,136 @@
1
+ <!doctype html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>JOE MCP Test</title>
6
+ <meta name="viewport" content="width=device-width, initial-scale=1">
7
+ <style>
8
+ body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Cantarell,Noto Sans,sans-serif;margin:20px;}
9
+ label{display:block;margin:8px 0 4px}
10
+ select, input, textarea, button{font-size:14px}
11
+ textarea{width:100%;height:160px;font-family:ui-monospace,Menlo,Consolas,monospace}
12
+ pre{background:#f6f8fa;border:1px solid #e1e4e8;padding:10px;overflow:auto}
13
+ .row{display:flex;gap:12px;align-items:center;flex-wrap:wrap}
14
+ .small{font-size:12px;color:#666}
15
+ .bad{color:#b00020}
16
+ .good{color:#0a7d00}
17
+ </style>
18
+ </head>
19
+ <body>
20
+ <h1>JOE MCP Test</h1>
21
+ <div class="small">Use this page to discover tools and call the JSON-RPC endpoint.</div>
22
+
23
+ <h3>Manifest</h3>
24
+ <div class="row">
25
+ <label for="base">Base URL</label>
26
+ <input id="base" value="" placeholder="http://localhost:{{PORT}}" style="min-width:280px"/>
27
+ <button id="loadManifest">Load manifest</button>
28
+ <span id="status" class="small"></span>
29
+ </div>
30
+ <label for="tool">Tools</label>
31
+ <select id="tool"></select>
32
+ <pre id="toolInfo"></pre>
33
+
34
+ <h3>Call JSON-RPC</h3>
35
+ <label for="params">Params (JSON)</label>
36
+ <textarea id="params">{}</textarea>
37
+ <div class="row">
38
+ <button id="call">POST /mcp</button>
39
+ <span id="callStatus" class="small"></span>
40
+ </div>
41
+ <pre id="result"></pre>
42
+
43
+ <script>
44
+ (function(){
45
+ const $ = (id)=>document.getElementById(id);
46
+ const base = $('base');
47
+ const loadBtn = $('loadManifest');
48
+ const status = $('status');
49
+ const toolSel = $('tool');
50
+ const toolInfo = $('toolInfo');
51
+ const params = $('params');
52
+ const callBtn = $('call');
53
+ const callStatus = $('callStatus');
54
+ const result = $('result');
55
+
56
+ // Try to infer base from window location
57
+ base.value = base.value || (location.origin);
58
+
59
+ let manifest = null;
60
+ let idCounter = 1;
61
+
62
+ function setStatus(el, msg, ok){
63
+ el.textContent = msg || '';
64
+ el.className = 'small ' + (ok===true?'good': ok===false?'bad':'');
65
+ }
66
+
67
+ async function fetchJSON(url, opts){
68
+ const res = await fetch(url, opts);
69
+ const ct = res.headers.get('content-type')||'';
70
+ const isJSON = ct.includes('application/json');
71
+ if(!res.ok){
72
+ let detail = isJSON ? await res.json().catch(()=>({})) : await res.text();
73
+ throw new Error('HTTP '+res.status+': '+(isJSON?JSON.stringify(detail):detail));
74
+ }
75
+ return isJSON ? res.json() : res.text();
76
+ }
77
+
78
+ loadBtn.onclick = async function(){
79
+ setStatus(status, 'Loading...', null);
80
+ toolSel.innerHTML = '';
81
+ toolInfo.textContent='';
82
+ try{
83
+ const url = base.value.replace(/\/$/,'') + '/.well-known/mcp/manifest.json';
84
+ manifest = await fetchJSON(url);
85
+ (manifest.tools||[]).forEach(t=>{
86
+ const opt=document.createElement('option');
87
+ opt.value=t.name; opt.textContent=t.name;
88
+ toolSel.appendChild(opt);
89
+ });
90
+ if((manifest.tools||[]).length){
91
+ toolSel.selectedIndex=0; renderToolInfo();
92
+ }
93
+ setStatus(status, 'Manifest loaded', true);
94
+ }catch(e){
95
+ setStatus(status, e.message||String(e), false);
96
+ }
97
+ };
98
+
99
+ function renderToolInfo(){
100
+ const name = toolSel.value;
101
+ const tool = (manifest.tools||[]).find(t=>t.name===name);
102
+ toolInfo.textContent = tool ? JSON.stringify(tool, null, 2) : '';
103
+ // Prefill common params for convenience
104
+ if(tool && tool.params){
105
+ params.value = JSON.stringify(Object.fromEntries(Object.keys(tool.params.properties||{}).map(k=>[k, null])), null, 2);
106
+ }
107
+ }
108
+ toolSel.onchange = renderToolInfo;
109
+
110
+ callBtn.onclick = async function(){
111
+ setStatus(callStatus, 'Calling...', null);
112
+ result.textContent='';
113
+ try{
114
+ const url = base.value.replace(/\/$/,'') + '/mcp';
115
+ let p = {};
116
+ try{ p = params.value ? JSON.parse(params.value) : {}; }catch(e){ throw new Error('Invalid JSON in params'); }
117
+ const body = {
118
+ jsonrpc: '2.0',
119
+ id: String(idCounter++),
120
+ method: toolSel.value,
121
+ params: p
122
+ };
123
+ const resp = await fetchJSON(url, { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)});
124
+ result.textContent = JSON.stringify(resp, null, 2);
125
+ setStatus(callStatus, 'OK', true);
126
+ }catch(e){
127
+ setStatus(callStatus, e.message||String(e), false);
128
+ }
129
+ };
130
+
131
+ // Auto-load manifest on open
132
+ setTimeout(()=>loadBtn.click(), 50);
133
+ })();
134
+ </script>
135
+ </body>
136
+ </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "json-object-editor",
3
- "version": "0.10.444",
3
+ "version": "0.10.501",
4
4
  "description": "JOE the Json Object Editor | Platform Edition",
5
5
  "main": "app.js",
6
6
  "scripts": {
package/readme.md CHANGED
@@ -5,6 +5,119 @@ JOE is software that allows you to manage data models via JSON objects. There ar
5
5
 
6
6
 
7
7
 
8
+ ## Architecture & Mental Model (Server)
9
+
10
+ - Global JOE
11
+ - Created in `server/init.js`; exposes subsystems like `JOE.Utils`, `JOE.Schemas`, `JOE.Storage`, `JOE.Mongo`/`JOE.MySQL`, `JOE.Cache`, `JOE.Apps`, `JOE.Server` (Express), `JOE.Sites`, `JOE.io` (Socket), and `JOE.auth`.
12
+ - Init pattern
13
+ - Modules can optionally export `init()`; `init.js` loads/watches modules and calls `init()` after `JOE.Server` is ready. This enables hot-reload and keeps `Server.js` thin.
14
+ - Schemas & events
15
+ - `JOE.Schemas` loads from `server/schemas/` and app schema dir into `JOE.Schemas.schema` with names in `JOE.Schemas.schemaList`. Raw copies live in `JOE.Schemas.raw_schemas` for event hooks.
16
+ - `JOE.Storage.save()` triggers schema events (`create`, `save`, `status`, `delete`) via `JOE.Schemas.events()` and writes history documents to `_history`.
17
+ - Storage & cache
18
+ - `JOE.Storage.load(collection, query, cb)` chooses backend per schema `storage.type` (`mongo`, `mysql`, `file`, `api`), with Mongo/file fallback.
19
+ - `JOE.Storage.save(item, collection, cb, { user, history })` emits `item_updated` to sockets, records history, and fires events.
20
+ - `JOE.Cache.update(cb, collections)` populates `JOE.Data`, flattens a `list`, and builds `lookup`. Use `JOE.Cache.findByID(collection, idOrCsv)` for fast lookups; `JOE.Cache.search(query)` for in-memory filtering.
21
+ - Auth
22
+ - `JOE.auth` middleware checks cookie token or Basic Auth; many API routes (and `/mcp`) are protected.
23
+ - Shorthand `$J`
24
+ - Server and client convenience: `$J.get(_id)`, `$J.search(query)`, `$J.schema(name)`.
25
+ - On server, provided by `server/modules/UniversalShorthand.js` and assigned to `global.$J` in `init.js`.
26
+ - MCP overview
27
+ - Manifest: `/.well-known/mcp/manifest.json`; JSON-RPC: `POST /mcp` (auth-protected). Tools map to real JOE APIs (`Schemas`, `Storage`, `Cache`) and sanitize sensitive fields.
28
+
29
+ ## MCP routes and local testing
30
+
31
+ - Endpoints
32
+ - Manifest (public): `GET /.well-known/mcp/manifest.json`
33
+ - JSON-RPC (auth): `POST /mcp`
34
+
35
+ - Auth
36
+ - If users exist, `POST /mcp` requires cookie or Basic Auth (same as other APIs). If no users configured, it is effectively open.
37
+
38
+ - Test page
39
+ - JOE ships a simple tester at `/_www/mcp-test.html` inside the package.
40
+ - Access via JOE path: `http://localhost:<PORT>/JsonObjectEditor/_www/mcp-test.html`
41
+ - If your host app serves its own `_www`, the tester can also be available at the root (fallback) if running with the updated server that mounts JOE’s `_www` as a secondary static directory. Then: `http://localhost:<PORT>/mcp-test.html`
42
+
43
+ - Tools
44
+ - `listSchemas(name?)`, `getSchema(name)`
45
+ - `getObject(_id, schema?)` (flattens by default; supports `depth` override)
46
+ - `search` (preferred): unified tool for cache and storage
47
+ - Params: `{ schema?, query?, ids?, source?: 'cache'|'storage', limit?, flatten?, depth? }`
48
+ - Defaults to cache across all collections; add `schema` to filter; set `source:"storage"` to query a specific schema in the DB.
49
+ - `saveObject({ object })`
50
+
51
+ - Quick tests (PowerShell)
52
+ - Prepare headers if using Basic Auth:
53
+ ```powershell
54
+ $pair = "user:pass"; $b64 = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($pair))
55
+ $h = @{ Authorization = "Basic $b64"; "Content-Type" = "application/json" }
56
+ $base = "http://localhost:<PORT>"
57
+ ```
58
+ - Manifest:
59
+ ```powershell
60
+ Invoke-RestMethod "$base/.well-known/mcp/manifest.json"
61
+ ```
62
+ - listSchemas:
63
+ ```powershell
64
+ $body = @{ jsonrpc="2.0"; id="1"; method="listSchemas"; params=@{} } | ConvertTo-Json -Depth 6
65
+ Invoke-RestMethod -Method Post -Uri "$base/mcp" -Headers $h -Body $body
66
+ ```
67
+ - getSchema:
68
+ ```powershell
69
+ $body = @{ jsonrpc="2.0"; id="2"; method="getSchema"; params=@{ name="<schemaName>" } } | ConvertTo-Json -Depth 6
70
+ Invoke-RestMethod -Method Post -Uri "$base/mcp" -Headers $h -Body $body
71
+ ```
72
+ - search (cache default):
73
+ ```powershell
74
+ $body = @{ jsonrpc="2.0"; id="3"; method="search"; params=@{ query=@{ itemtype="<schemaName>" }; limit=10 } } | ConvertTo-Json -Depth 10
75
+ Invoke-RestMethod -Method Post -Uri "$base/mcp" -Headers $h -Body $body
76
+ ```
77
+ - search (storage):
78
+ ```powershell
79
+ $body = @{ jsonrpc="2.0"; id="4"; method="search"; params=@{ schema="<schemaName>"; source="storage"; query=@{ }; limit=10 } } | ConvertTo-Json -Depth 10
80
+ Invoke-RestMethod -Method Post -Uri "$base/mcp" -Headers $h -Body $body
81
+ ```
82
+ - search (ids + flatten):
83
+ ```powershell
84
+ $body = @{ jsonrpc="2.0"; id="5"; method="search"; params=@{ schema="<schemaName>"; ids=@("<id1>","<id2>"); flatten=$true; depth=2 } } | ConvertTo-Json -Depth 10
85
+ Invoke-RestMethod -Method Post -Uri "$base/mcp" -Headers $h -Body $body
86
+ ```
87
+ - saveObject:
88
+ ```powershell
89
+ $object = @{ itemtype="<schemaName>"; name="Test via MCP" }
90
+ $body = @{ jsonrpc="2.0"; id="4"; method="saveObject"; params=@{ object=$object } } | ConvertTo-Json -Depth 10
91
+ Invoke-RestMethod -Method Post -Uri "$base/mcp" -Headers $h -Body $body
92
+ ```
93
+
94
+ - Quick tests (curl)
95
+ - Manifest:
96
+ ```bash
97
+ curl -s http://localhost:<PORT>/.well-known/mcp/manifest.json | jq
98
+ ```
99
+ - listSchemas:
100
+ - search (cache):
101
+ ```bash
102
+ curl -s -X POST http://localhost:<PORT>/mcp \
103
+ -H 'Content-Type: application/json' \
104
+ -d '{"jsonrpc":"2.0","id":"3","method":"search","params":{"query":{"itemtype":"<schemaName>"},"limit":10}}' | jq
105
+ ```
106
+ - search (storage):
107
+ ```bash
108
+ curl -s -X POST http://localhost:<PORT>/mcp \
109
+ -H 'Content-Type: application/json' \
110
+ -d '{"jsonrpc":"2.0","id":"4","method":"search","params":{"schema":"<schemaName>","source":"storage","query":{},"limit":10}}' | jq
111
+ ```
112
+ ```bash
113
+ curl -s -X POST http://localhost:<PORT>/mcp \
114
+ -H 'Content-Type: application/json' \
115
+ -d '{"jsonrpc":"2.0","id":"1","method":"listSchemas","params":{}}' | jq
116
+ ```
117
+
118
+ - Troubleshooting
119
+ - If you see a payload like `{ originalURL: "/...", site: "no site found" }`, the request hit the Sites catch-all. Ensure MCP routes are initialized before Sites (handled by default in `server/init.js` via `MCP.init()`), and use the correct URL: `/.well-known/mcp/manifest.json` or `/mcp`.
120
+
8
121
  ## SERVER/PLATFORM mode
9
122
  check port 2099
10
123
  /JOE/
package/server/init.js CHANGED
@@ -97,6 +97,13 @@ var app = function(config){
97
97
  global.$J = require('./modules/UniversalShorthand.js');
98
98
  function initServers(){
99
99
  JOE.Server = require('./modules/Server.js');
100
+ // Attach MCP routes before Sites catch-all
101
+ try {
102
+ const MCP = require('./modules/MCP.js');
103
+ if (MCP && MCP.init) MCP.init();
104
+ } catch (e) {
105
+ console.log('[MCP] attach error:', e && e.message);
106
+ }
100
107
 
101
108
  JOE.Sites = require('./modules/Sites.js');
102
109
  JOE.io = require('./modules/Socket.js');
@@ -0,0 +1,310 @@
1
+ // modules/MCP.js
2
+
3
+ /**
4
+ * Model Context Protocol (MCP) core module for JOE.
5
+ * This module provides a JSON-RPC 2.0 compatible interface to JOE objects and schemas.
6
+ * Agents (like OpenAI Assistants) can discover and call structured tools via manifest + POST.
7
+ */
8
+
9
+ const MCP = {};
10
+ const { Storage, Schemas } = global.JOE; // Adjust as needed based on how your modules are wired
11
+
12
+ // Internal helpers
13
+ function loadFromStorage(collection, query) {
14
+ return new Promise((resolve, reject) => {
15
+ try {
16
+ Storage.load(collection, query || {}, function(err, results){
17
+ if (err) return reject(err);
18
+ resolve(results || []);
19
+ });
20
+ } catch (e) {
21
+ reject(e);
22
+ }
23
+ });
24
+ }
25
+
26
+ function sanitizeItems(items) {
27
+ try {
28
+ const arr = Array.isArray(items) ? items : [items];
29
+ return arr.map(i => {
30
+ if (!i || typeof i !== 'object') return i;
31
+ const copy = JSON.parse(JSON.stringify(i));
32
+ if (copy.password) copy.password = null;
33
+ if (copy.token) copy.token = null;
34
+ return copy;
35
+ });
36
+ } catch (e) {
37
+ return Array.isArray(items) ? items : [items];
38
+ }
39
+ }
40
+
41
+ // ----------------------
42
+ // TOOL DEFINITIONS
43
+ // ----------------------
44
+ // This object maps tool names to actual execution functions.
45
+ // Each function takes a `params` object and returns a JSON-serializable result.
46
+ MCP.tools = {
47
+
48
+ // List all schema names in the system
49
+ listSchemas: async (_params, _ctx) => {
50
+ const list = (Schemas && (
51
+ (Schemas.schemaList && Schemas.schemaList.length && Schemas.schemaList) ||
52
+ (Schemas.schema && Object.keys(Schemas.schema))
53
+ )) || [];
54
+ return list.slice().sort();
55
+ },
56
+
57
+ // Get full schema definition by name
58
+ getSchema: async ({ name }, _ctx) => {
59
+ if (!name) throw new Error("Missing required param 'name'");
60
+ const def = Schemas.schema && Schemas.schema[name];
61
+ if (!def) throw new Error(`Schema "${name}" not found`);
62
+ return def;
63
+ },
64
+
65
+ // Convenience: fetch a single object by _id (schema optional). Prefer cache; fallback to storage.
66
+ getObject: async ({ _id, schema, flatten = true, depth = 1 }, _ctx) => {
67
+ if (!_id) throw new Error("Missing required param '_id'");
68
+ // Fast path via global lookup
69
+ let obj = (JOE && JOE.Cache && JOE.Cache.findByID) ? (JOE.Cache.findByID(_id) || null) : null;
70
+ if (!obj && schema) {
71
+ const results = await loadFromStorage(schema, { _id });
72
+ obj = (results && results[0]) || null;
73
+ }
74
+ if (!obj && schema && JOE && JOE.Cache && JOE.Cache.findByID) {
75
+ obj = JOE.Cache.findByID(schema, _id) || null;
76
+ }
77
+ if (!obj) throw new Error(`Object not found${schema?(' in '+schema):''} with _id: ${_id}`);
78
+ if (flatten && JOE && JOE.Utils && JOE.Utils.flattenObject) {
79
+ try { return sanitizeItems(JOE.Utils.flattenObject(_id, { recursive: true, depth }))[0]; } catch(e) {}
80
+ }
81
+ return sanitizeItems(obj)[0];
82
+ },
83
+
84
+ /* Deprecated: use unified 'search' instead
85
+ getObjectsByIds: async () => { throw new Error('Use search with ids instead'); },
86
+ queryObjects: async () => { throw new Error('Use search instead'); },
87
+ */
88
+
89
+ /* Deprecated: use unified 'search' instead
90
+ searchCache: async () => { throw new Error('Use search instead'); },
91
+ */
92
+
93
+ // Unified search: defaults to cache; set source="storage" to query DB for a schema
94
+ search: async ({ schema, query = {}, ids, source = 'cache', limit = 50, flatten = false, depth = 1 }, _ctx) => {
95
+ const useCache = !source || source === 'cache';
96
+ const useStorage = source === 'storage';
97
+
98
+ if (ids && !Array.isArray(ids)) throw new Error("'ids' must be an array if provided");
99
+
100
+ // When ids are provided and a schema is known, prefer cache for safety/speed
101
+ if (Array.isArray(ids) && schema) {
102
+ let items = [];
103
+ if (JOE && JOE.Cache && JOE.Cache.findByID) {
104
+ const found = JOE.Cache.findByID(schema, ids.join(',')) || [];
105
+ items = Array.isArray(found) ? found : (found ? [found] : []);
106
+ }
107
+ if (useStorage && (!items || items.length === 0)) {
108
+ try {
109
+ const fromStorage = await loadFromStorage(schema, { _id: { $in: ids } });
110
+ items = fromStorage || [];
111
+ } catch (e) { /* ignore storage errors here */ }
112
+ }
113
+ if (flatten && JOE && JOE.Utils && JOE.Utils.flattenObject) {
114
+ try { items = ids.map(id => JOE.Utils.flattenObject(id, { recursive: true, depth })); } catch (e) {}
115
+ }
116
+ const sliced = (typeof limit === 'number' && limit > 0) ? items.slice(0, limit) : items;
117
+ return { items: sanitizeItems(sliced) };
118
+ }
119
+
120
+ // No ids: choose source
121
+ if (useCache) {
122
+ if (!JOE || !JOE.Cache || !JOE.Cache.search) throw new Error('Cache not initialized');
123
+ let results = JOE.Cache.search(query || {});
124
+ if (schema) results = (results || []).filter(i => i && i.itemtype === schema);
125
+ const sliced = (typeof limit === 'number' && limit > 0) ? results.slice(0, limit) : results;
126
+ return { items: sanitizeItems(sliced) };
127
+ }
128
+
129
+ if (useStorage) {
130
+ if (!schema) throw new Error("'schema' is required when source=storage");
131
+ const results = await loadFromStorage(schema, query || {});
132
+ const sliced = (typeof limit === 'number' && limit > 0) ? (results || []).slice(0, limit) : (results || []);
133
+ if (flatten && JOE && JOE.Utils && JOE.Utils.flattenObject) {
134
+ try { return { items: sanitizeItems(sliced.map(it => JOE.Utils.flattenObject(it && it._id, { recursive: true, depth }))) }; } catch (e) {}
135
+ }
136
+ return { items: sanitizeItems(sliced) };
137
+ }
138
+
139
+ throw new Error("Invalid 'source'. Use 'cache' (default) or 'storage'.");
140
+ },
141
+
142
+ // Save an object via Storage (respects events/history)
143
+ saveObject: async ({ object }, ctx = {}) => {
144
+ if (!object || !object.itemtype) throw new Error("'object' with 'itemtype' is required");
145
+ const user = (ctx.req && ctx.req.User) ? ctx.req.User : { name: 'anonymous' };
146
+ const saved = await new Promise((resolve, reject) => {
147
+ try {
148
+ Storage.save(object, object.itemtype, function(err, data){
149
+ if (err) return reject(err);
150
+ resolve(data);
151
+ }, { user });
152
+ } catch (e) { reject(e); }
153
+ });
154
+ return sanitizeItems(saved)[0];
155
+ }
156
+
157
+ // 🔧 Add more tools here as needed
158
+ };
159
+
160
+ // ----------------------
161
+ // METADATA FOR TOOLS
162
+ // ----------------------
163
+ // These are used to auto-generate the MCP manifest from the function registry
164
+ MCP.descriptions = {
165
+ listSchemas: "List all available JOE schema names.",
166
+ getSchema: "Retrieve a full schema definition by name.",
167
+ getObject: "Fetch a single object by _id (schema optional). Flattens by default.",
168
+ // getObjectsByIds: "Deprecated - use 'search' with ids.",
169
+ // queryObjects: "Deprecated - use 'search'.",
170
+ // searchCache: "Deprecated - use 'search'.",
171
+ search: "Unified search. Defaults to cache; set source=storage to query DB.",
172
+ saveObject: "Create/update an object; triggers events/history."
173
+ };
174
+
175
+ MCP.params = {
176
+ listSchemas: {},
177
+ getSchema: {
178
+ type: "object",
179
+ properties: {
180
+ name: { type: "string" }
181
+ },
182
+ required: ["name"]
183
+ },
184
+ getObject: {
185
+ type: "object",
186
+ properties: {
187
+ _id: { type: "string" },
188
+ schema: { type: "string" },
189
+ flatten: { type: "boolean" },
190
+ depth: { type: "integer" }
191
+ },
192
+ required: ["_id"]
193
+ },
194
+ // getObjectsByIds: { ...deprecated },
195
+ // queryObjects: { ...deprecated },
196
+ // searchCache: { ...deprecated },
197
+ search: {
198
+ type: "object",
199
+ properties: {
200
+ schema: { type: "string" },
201
+ query: { type: "object" },
202
+ ids: { type: "array", items: { type: "string" } },
203
+ source: { type: "string", enum: ["cache","storage"] },
204
+ limit: { type: "integer" },
205
+ flatten: { type: "boolean" },
206
+ depth: { type: "integer" }
207
+ },
208
+ required: []
209
+ },
210
+ saveObject: {
211
+ type: "object",
212
+ properties: {
213
+ object: { type: "object" }
214
+ },
215
+ required: ["object"]
216
+ }
217
+ };
218
+
219
+ MCP.returns = {
220
+ listSchemas: {
221
+ type: "array",
222
+ items: { type: "string" }
223
+ },
224
+ getSchema: { type: "object" },
225
+ getObject: { type: "object" },
226
+ // getObjectsByIds: { ...deprecated },
227
+ // queryObjects: { ...deprecated },
228
+ // searchCache: { ...deprecated },
229
+ search: {
230
+ type: "object",
231
+ properties: {
232
+ items: { type: "array", items: { type: "object" } }
233
+ }
234
+ },
235
+ saveObject: { type: "object" }
236
+ };
237
+
238
+ // ----------------------
239
+ // MANIFEST HANDLER
240
+ // ----------------------
241
+ // Responds to GET /.well-known/mcp/manifest.json
242
+ // Returns tool descriptions for agent discovery
243
+ MCP.manifest = async function (req, res) {
244
+ try {
245
+ const toolNames = Object.keys(MCP.tools);
246
+ const tools = toolNames.map(name => ({
247
+ name,
248
+ description: MCP.descriptions[name],
249
+ params: MCP.params[name],
250
+ returns: MCP.returns[name]
251
+ }));
252
+ return res.json({ version: "1.0", tools });
253
+ } catch (e) {
254
+ console.log('[MCP] manifest error:', e);
255
+ return res.status(500).json({ error: e.message || 'manifest error' });
256
+ }
257
+ };
258
+
259
+ // ----------------------
260
+ // JSON-RPC HANDLER
261
+ // ----------------------
262
+ // Responds to POST /mcp with JSON-RPC 2.0 calls
263
+ MCP.rpcHandler = async function (req, res) {
264
+ const { id, method, params } = req.body;
265
+
266
+ // Validate method
267
+ if (!MCP.tools[method]) {
268
+ return res.status(400).json({
269
+ jsonrpc: "2.0",
270
+ id,
271
+ error: { code: -32601, message: "Method not found" }
272
+ });
273
+ }
274
+
275
+ try {
276
+ const result = await MCP.tools[method](params, { req, res });
277
+ return res.json({ jsonrpc: "2.0", id, result });
278
+ } catch (err) {
279
+ console.error(`[MCP] Error in method ${method}:`, err);
280
+ return res.status(500).json({
281
+ jsonrpc: "2.0",
282
+ id,
283
+ error: { code: -32000, message: err.message || "Internal error" }
284
+ });
285
+ }
286
+ };
287
+
288
+ module.exports = MCP;
289
+
290
+ // Optional initializer to attach routes without modifying Server.js
291
+ MCP.init = function initMcpRoutes(){
292
+ try {
293
+ if (!global.JOE || !JOE.Server) return;
294
+ if (JOE._mcpInitialized) return;
295
+ const server = JOE.Server;
296
+ const auth = JOE.auth; // may be undefined for manifest
297
+ server.get('/.well-known/mcp/manifest.json', function(req, res){
298
+ return MCP.manifest(req, res);
299
+ });
300
+ if (auth) {
301
+ server.post('/mcp', auth, function(req, res){ return MCP.rpcHandler(req, res); });
302
+ } else {
303
+ server.post('/mcp', function(req, res){ return MCP.rpcHandler(req, res); });
304
+ }
305
+ JOE._mcpInitialized = true;
306
+ console.log('[MCP] routes attached');
307
+ } catch (e) {
308
+ console.log('[MCP] init error:', e);
309
+ }
310
+ };
@@ -106,7 +106,6 @@ server.use(function(req, res, next) {
106
106
  });
107
107
  server.use(JOE.webconfig.joepath,express.static(JOE.joedir));
108
108
 
109
-
110
109
  //USER
111
110
  server.get(['/API/user/:method'],auth,function(req,res,next){
112
111
  var users = (JOE.Data && JOE.Data.user) || [];
@@ -809,6 +808,8 @@ JOE.Utils.setupFileFolder(webDir,'web');
809
808
 
810
809
 
811
810
  server.use('/',express.static(JOE.webDir));
811
+ // Also serve JOE's own _www as a fallback under root (parent app takes priority)
812
+ server.use('/',express.static(path.join(JOE.joedir, JOE.webconfig.webDir)));
812
813
 
813
814
  http.listen(JOE.webconfig.port,function(){
814
815
  //console.log('joe listening on '+JOE.webconfig.port);