Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
8f3c883
fix(canvas): route Delete key and halo button through authoring state…
Sep 23, 2026
e94e20d
feat(shacl): enrich violation messages with rdfs:labels and improve t…
Sep 24, 2026
531dbcd
feat(relay): add FhGenie stop-button streaming detection; scope getGr…
Sep 24, 2026
6edfb82
refactor(relay): unify canvas summary with getGraphState; drop getNod…
Sep 24, 2026
3538187
feat(relay): lock relay to selected Ontosphere tab (session targeting)
Sep 24, 2026
adfa3af
feat(relay): incremental injection with pending-count hints for multi…
Sep 24, 2026
bb04293
fix(relay): revert incremental injection; keep streaming guard in poll
Sep 24, 2026
d60d924
fix(relay): replace isAiStreaming() poll guard with 2-poll stability …
Sep 24, 2026
d1b7c7e
feat(relay): block calls when no tab locked; fast session discovery v…
Sep 24, 2026
69428a3
fix(relay): strict bidirectional session pairing; block old-code tabs
Sep 24, 2026
a590924
fix(relay): revert to isAiStreaming() guard; add 3-min batch timeout
Sep 24, 2026
dde74fc
fix(relay): block poll during active injection to prevent dropped res…
Sep 24, 2026
0a883cc
feat(webmcp): add TypeScript types and document.modelContext polyfill
Sep 24, 2026
72d583c
feat(webmcp): migrate MCP registration to document.modelContext + obj…
Sep 24, 2026
d117d9e
feat(webmcp): update relay UI description and starter prompt with Web…
Sep 24, 2026
37db5cd
feat(webmcp): full spec compliance — toolchange events and signal unr…
Sep 24, 2026
72f60ba
feat(relay): add Gemini support and fix streaming detection
Sep 24, 2026
ba1c6c1
chore(release): bump version to 1.7.6 and add changelog
Sep 24, 2026
4bde1ff
test(e2e): seed lockedSessionId via sessionSelect in relay origin test
Sep 24, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Changelog

## [1.7.6] — 2026-09-24

### New features

**WebMCP support (document.modelContext)**
- Full [WebMCP spec](https://webmachinelearning.github.io/webmcp/) compliance: `document.modelContext` polyfill, object-form `registerTool`, `toolchange` events, and signal-based unregistration
- TypeScript types for the polyfill and WebMCP surface
- Test suite covering polyfill registration, toolchange dispatch, and signal cleanup

**AI Relay Bridge — Gemini support**
- Input detection for Gemini's `rich-textarea` contenteditable component
- Send-button detection via `aria-label="Send message"` with visibility guard (Gemini hides the send button with a CSS `hidden` class during generation instead of using `disabled`)
- Streaming detection covers both `"Stop generating"` and `"Stop response"` button label variants

**AI Relay Bridge — reliability improvements**
- Session locking: relay popup binds to a specific Ontosphere tab; stale-tab messages are dropped
- Fast session discovery via ping rather than waiting for the next poll cycle
- 3-minute batch timeout with partial-result flush when individual tool calls hang
- Incremental injection with pending-count hints for multi-call batches
- Injection guard blocks new polls while a result is being inserted, preventing dropped results
- FhGenie stop-button streaming detection (DismissSquare icon path)
- `getGraphState` scoped by graph list; unified with canvas summary

**SHACL violations**
- Violation messages enriched with `rdfs:label` values for human-readable property and class names
- Improved tooltip readability in the SHACL shapes panel

### Bug fixes

- **Canvas**: `Delete` key and halo delete button now route through the authoring state machine; nodes no longer reappear after save when deleted via keyboard
- **Relay**: reverted polling strategy to `isAiStreaming()` guard after stability regression; added two-poll idle streak requirement before injection to prevent the UUID-echo bug on OWUI
- **Relay**: strict bidirectional session pairing blocks tabs running old bookmarklet code

### Breaking changes

None. The WebMCP polyfill is opt-in and backwards-compatible with the existing `window.__mcpTools` registration path.
122 changes: 97 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,10 @@
- [Agent edit provenance](#agent-edit-provenance)
- [Recommended workflow](#recommended-workflow)
- [Using Ontosphere with any AI](#using-ontosphere-with-any-ai)
- [Browser console](#browser-console)
- [Claude Code / Playwright](#claude-code--playwright-full-automation)
- [AI Relay Bridge (ChatGPT, Gemini, Claude.ai)](#chatgpt-gemini-claudeai--ai-relay-bridge)
- [WebMCP native (Chrome 153+)](#webmcp-native-chrome-153)
- **Developer**
- [Quick start (development)](#quick-start-development)
- [Reasoning demo (OWL 2 DL patterns)](#reasoning-demo-owl-2-dl-patterns)
Expand Down Expand Up @@ -121,7 +123,7 @@ Everything below runs in the browser tab, against an in-memory RDF store backed
- **PROV-O provenance** of every agent edit, with diff and one-click **reversal** of a batch (faithful to typed and language-tagged literals), and a warning when retention truncates reversible history.

#### 🤖 AI / MCP integration — 43 tools
Exposes a [Model Context Protocol](https://modelcontextprotocol.io) server via the browser's `navigator.modelContext` API, across nine categories (manifest at `/.well-known/mcp.json`):
Exposes a [Model Context Protocol](https://modelcontextprotocol.io) tool surface via the browser's [`document.modelContext` WebMCP API](https://webmachinelearning.github.io/webmcp/) (W3C CG, native in Chrome 153+; polyfill included for all other browsers), across nine categories (manifest at `/.well-known/mcp.json`):

| Category | Tools |
|---|---|
Expand Down Expand Up @@ -497,22 +499,71 @@ loadOntology (TBox)

### Using Ontosphere with any AI

The demo scripts work against the **live deployment** — no local server needed. Any AI that can drive a browser (Claude Code, headless Playwright, computer-use agents) can use Ontosphere directly via its MCP tools.
Ontosphere exposes its full tool surface through several transport paths. Choose based on your AI's execution environment:

| Transport | AI environment | Backend needed? | Setup effort |
|-----------|---------------|-----------------|--------------|
| [Browser console](#browser-console) | Human operator / devtools | None | None |
| [Claude Code + Playwright](#claude-code--playwright-full-automation) | Claude Code CLI, headless scripts | None | Low |
| [AI Relay Bridge](#chatgpt-gemini-claudeai--ai-relay-bridge) | ChatGPT, Claude.ai, Gemini chat | None | One bookmarklet drag |
| [WebMCP native](#webmcp-native-chrome-153) | Chrome 153+ AI-aware browser | None | None (built-in) |

All paths share the same 43 tools and the same `McpResult` return shape — the transport is the only difference.

---

#### Browser console

Ontosphere registers every tool on `window.__mcpTools` at startup. Open DevTools on any Ontosphere tab and call tools directly:

```js
// Discover tools
await window.__mcpTools['help']({})

// Add a node
await window.__mcpTools['addNode']({ iri: 'ex:Alice', label: 'Alice', typeIri: 'foaf:Person' })

// Run reasoning
await window.__mcpTools['runReasoning']({})
```

Results are returned as `{ success: true, data: ... }` or `{ success: false, error: "..." }`.

This is the simplest path — useful for one-off commands, debugging, or when scripting from the DevTools console.

---

#### Claude Code / Playwright (full automation)

Point the demo scripts at the deployed app:
Any AI that can run JavaScript in a browser page — Claude Code with the [Playwright MCP server](https://github.com/microsoft/playwright-mcp), headless Playwright scripts, or computer-use agents — can call tools directly via `window.__mcpTools` without a relay.

**Claude Code example** (using `mcp__playwright__browser_evaluate`):

```js
// Navigate to Ontosphere first, then call any tool:
await window.__mcpTools['addNode']({ iri: 'ex:Alice', label: 'Alice', typeIri: 'foaf:Person' })
await window.__mcpTools['runReasoning']({})
await window.__mcpTools['exportImage']({ format: 'svg' })
```

**Run the built-in demo scripts** against the live deployment:

```sh
node scripts/mcp-demo-reasoning.mjs --url https://thhanke.github.io/ontosphere
node scripts/mcp-demo-foaf.mjs --url https://thhanke.github.io/ontosphere
```

The script opens a headless browser, navigates to the URL, registers the MCP tools, then drives the full workflow — building TBox + ABox, running reasoning, taking snapshots, exporting Turtle — exactly as shown in the demo documents.
These scripts open a headless browser, navigate to Ontosphere, and drive the full workflow — building TBox + ABox, running reasoning, taking snapshots, and exporting Turtle — exactly as shown in the [demo documents](#demo).

Full tool declarations with input schemas: [public/.well-known/mcp.json](public/.well-known/mcp.json)

---

#### ChatGPT, Gemini, Claude.ai — AI Relay Bridge

The **AI Relay Bridge** connects any AI chat tab to Ontosphere with no server, extension, or copy-paste. A bookmarklet watches the AI's output for backtick-wrapped JSON-RPC 2.0 tool calls, executes them in Ontosphere via a BroadcastChannel popup, and injects JSON-RPC responses back into the chat input automatically.
When the AI lives inside a chat UI and cannot execute JavaScript directly, the **AI Relay Bridge** closes the gap. A bookmarklet watches the AI's output for backtick-wrapped JSON-RPC 2.0 tool calls, executes them in Ontosphere via a BroadcastChannel popup, and injects the results back into the chat input — all in the browser, no server required.

> **Why BroadcastChannel instead of WebMCP?** The [WebMCP spec](https://webmachinelearning.github.io/webmcp/) limits `document.modelContext` tool execution to the same frame tree. A chat tab (claude.ai, chatgpt.com) and the Ontosphere tab are unrelated browsing contexts and cannot share tools natively. The relay popup bridges them via BroadcastChannel as a conformant complement to the spec.

➡️ **[Full setup guide: docs/relay-bridge.md](docs/relay-bridge.md)**

Expand All @@ -521,21 +572,47 @@ The **AI Relay Bridge** connects any AI chat tab to Ontosphere with no server, e
2. Drag the **Ontosphere Relay** button to your browser bookmark bar
3. Go to your AI chat tab and click the bookmark — a small relay popup opens

**Starter prompt** (paste into your AI chat after clicking the bookmarklet):
**Starter prompt** (copy from the relay panel, or paste manually):

```text
You are connected to Ontosphere via a relay. A script in this tab intercepts your tool calls, runs them in Ontosphere, and injects results back as a user message. If a tool call returns success:false, read the error, fix the argument, and retry the same call immediately — never skip a failed call. Ask the user what they would like to build.
I'm using Ontosphere's browser-based MCP integration. Ontosphere implements the W3C WebMCP API
(document.modelContext) with a polyfill for browsers without native support (Chrome 153+ has it natively).

Output format — one JSON-RPC 2.0 call per line, backtick-wrapped:
`{"jsonrpc":"2.0","id":<N>,"method":"tools/call","params":{"name":"<toolName>","arguments":{...}}}`
How the relay works: a bookmarklet on this page watches your responses for backtick-wrapped JSON-RPC 2.0
tool calls. It forwards each call via postMessage to a relay popup, which bridges to the Ontosphere tab
via BroadcastChannel — necessary because WebMCP tool execution is scoped to the same frame tree and
unrelated tabs cannot share document.modelContext tools directly. Results from the live knowledge-graph
instance are injected back into this chat automatically.

Call help first to get full instructions and the tool list:
Format — one call per response line, backtick-wrapped:
`{"jsonrpc":"2.0","id":<N>,"method":"tools/call","params":{"name":"<tool>","arguments":{...}}}`

The results are live graph state, not simulated. You can decline; I'll run commands manually. If you're
willing, call help first to get the tool list:
`{"jsonrpc":"2.0","id":0,"method":"tools/call","params":{"name":"help","arguments":{}}}`
```

The relay handles execution and result feedback automatically — no manual copy-paste needed.
The relay handles execution and result injection automatically — no manual copy-paste needed.

Full tool declarations with input schemas: [public/.well-known/mcp.json](public/.well-known/mcp.json)
---

#### WebMCP native (Chrome 153+)

Ontosphere registers all tools via [`document.modelContext.registerTool()`](https://webmachinelearning.github.io/webmcp/) at startup. In Chrome 153+ (with the WebMCP origin trial enabled), an AI agent running in the same browsing context can discover and execute tools natively:

```js
// Discover tools
const tools = await document.modelContext.getTools()

// Execute a tool
const result = await document.modelContext.executeTool(
tools.find(t => t.name === 'addNode'),
{ iri: 'ex:Alice', label: 'Alice', typeIri: 'foaf:Person' }
)
// result is a JSON string: '{"success":true,"data":{...}}'
```

In browsers without native support, a conformant polyfill (`src/webmcp/polyfill.ts`) provides the same API. The `window.__mcpTools` path (above) remains available as a fallback regardless of browser.

---

Expand Down Expand Up @@ -570,30 +647,25 @@ Developer

### Setup (Playwright / headless)

`navigator.modelContext` does not exist in headless Chromium. Inject the polyfill **before** the page loads using `page.addInitScript`:
`document.modelContext` does not exist in headless Chromium. Ontosphere ships a conformant polyfill (`src/webmcp/polyfill.ts`) that installs automatically on app load — but for headless use you can also inject a minimal shim via `page.addInitScript` **before** the page loads:

```js
await page.addInitScript(() => {
const tools = {};
Object.defineProperty(navigator, 'modelContext', {
value: { registerTool: async (n, _d, _s, h) => { tools[n] = h; } },
configurable: true,
});
const shim = { registerTool: async (tool) => { tools[tool.name] = tool.execute; } };
Object.defineProperty(document, 'modelContext', { value: shim, configurable: true });
// alias for any legacy callers that use navigator.modelContext
Object.defineProperty(navigator, 'modelContext', { get: () => document.modelContext });
window.__mcpTools = tools;
});

// After page load:
await page.evaluate(async () => {
const mod = await import('/src/mcp/ontosphereMcpServer.ts');
await mod.registerMcpTools();
});

// Call a tool:
// After page load — tools register automatically via the shim.
// You can also call them directly:
await page.evaluate(async ([name, params]) => window.__mcpTools[name](params),
['addNode', { iri: 'ex:alice', typeIri: 'foaf:Person', label: 'Alice' }]);
```

In a browser with native `navigator.modelContext`, tools register automatically on app load.
In a browser with native `document.modelContext` (Chrome 153+), tools register automatically on app load without any shim.

### URL parameters (MCP)

Expand Down
11 changes: 11 additions & 0 deletions e2e/relay-origin-allowlist.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,17 @@ test.describe('relay.html — opener-origin trust model (security)', () => {
if (d && d.type === 'vg-call') seen.push({ type: d.type, tool: d.tool });
};

// Seed a locked session so the "no tab locked" guard does not block forwarding.
// lockedSessionId is a closure variable; the only write path is the sessionSelect
// change listener. Add a synthetic option, select it, and dispatch 'change'.
const sel = document.getElementById('session-select') as HTMLSelectElement;
const opt = document.createElement('option');
opt.value = 'test-session-id';
opt.textContent = 'Test tab [test-session-id]';
sel.appendChild(opt);
sel.value = 'test-session-id';
sel.dispatchEvent(new Event('change'));

function fire(originStr: string, tool: string) {
window.dispatchEvent(new MessageEvent('message', {
data: { type: 'vg-call', tool, requestId: 'rq-test', params: {} },
Expand Down
10 changes: 9 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "ontosphere",
"description": "Browser-based interactive RDF/ontology knowledge graph editor — authoring, OWL 2 DL reasoning (Konclude), clustering, multi-algorithm layout, and MCP support. Runs entirely client-side.",
"version": "1.7.5",
"version": "1.7.6",
"license": "Apache-2.0",
"author": "Thomas Hanke <thomas.hnke82@gmail.com> (https://github.com/ThHanke)",
"homepage": "https://thhanke.github.io/ontosphere/",
Expand Down Expand Up @@ -158,7 +158,8 @@
"typescript": "^5.9.3",
"typescript-eslint": "^8.46.3",
"vite": "^7.1.12",
"vitest": "^4.0.6"
"vitest": "^4.0.6",
"webmcp-types": "^0.1.9"
},
"vitest": {
"environment": "jsdom",
Expand Down
Loading
Loading