fraise-mcp 0.1.1__tar.gz
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.
- fraise_mcp-0.1.1/PKG-INFO +62 -0
- fraise_mcp-0.1.1/README.md +48 -0
- fraise_mcp-0.1.1/pyproject.toml +40 -0
- fraise_mcp-0.1.1/pyproject.toml.orig +38 -0
- fraise_mcp-0.1.1/src/fraise_mcp/__init__.py +32 -0
- fraise_mcp-0.1.1/src/fraise_mcp/cli.py +129 -0
- fraise_mcp-0.1.1/src/fraise_mcp/py.typed +0 -0
- fraise_mcp-0.1.1/src/fraise_mcp/server.py +591 -0
- fraise_mcp-0.1.1/src/fraise_mcp/statement.py +182 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: fraise-mcp
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Fraise MCP server: remember and recall over a running Fraise daemon, with vectors embedded locally
|
|
5
|
+
Author: René-Jean Corneille
|
|
6
|
+
Author-email: René-Jean Corneille <corneille.r.j@gmail.com>
|
|
7
|
+
Requires-Dist: fraise-sdk[fastembed]>=0.4.1
|
|
8
|
+
Requires-Dist: mcp>=2.3.0,<3
|
|
9
|
+
Requires-Dist: pytest>=9.1.1 ; extra == 'dev'
|
|
10
|
+
Requires-Dist: pytest-cov>=7.1.0 ; extra == 'dev'
|
|
11
|
+
Requires-Python: >=3.12
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# fraise-mcp
|
|
16
|
+
|
|
17
|
+
An MCP server for a running [Fraise](https://github.com/FraiseHQ/fraise) daemon. It exposes two tools, `recall` and `remember`, each taking one FQL statement: `recall` runs every read, a recall, a `when` or a `describe` in front of a recall, and `remember` every write. It embeds every statement's text locally so retrieval is hybrid (text and vector) out of the box. The model writes plain FQL and never a vector.
|
|
18
|
+
|
|
19
|
+
<!-- mcp-name: io.github.FraiseHQ/fraise -->
|
|
20
|
+
|
|
21
|
+
## Run
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
uvx fraise-mcp
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Register it with your agent host:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
claude mcp add fraise -- uvx fraise-mcp
|
|
31
|
+
codex mcp add fraise -- uvx fraise-mcp
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The server forwards to a daemon that runs separately (`brew services start fraise`, or `systemctl --user start fraise`), like a database behind a connection URL.
|
|
35
|
+
|
|
36
|
+
## Provenance
|
|
37
|
+
|
|
38
|
+
Every release is published to PyPI from this repository's release workflow, with a [PEP 740](https://peps.python.org/pep-0740/) attestation that PyPI shows as the file's provenance. A downloaded file verifies against the repository:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
uvx pypi-attestations verify pypi --repository https://github.com/FraiseHQ/fraise pypi:fraise_mcp-<version>-py3-none-any.whl
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Configure
|
|
45
|
+
|
|
46
|
+
Every setting is a flag, and each flag falls back to an environment variable:
|
|
47
|
+
|
|
48
|
+
| Flag | Environment | Default |
|
|
49
|
+
| --- | --- | --- |
|
|
50
|
+
| `--addr` | `FRAISE_ADDR` | `http://localhost:9876` |
|
|
51
|
+
| `--model` | `FRAISE_EMBEDDING_MODEL` | `BAAI/bge-small-en-v1.5` |
|
|
52
|
+
| `--no-vectors` | `FRAISE_NO_VECTORS=1` | vectors on |
|
|
53
|
+
|
|
54
|
+
The model is any text model [fastembed](https://qdrant.github.io/fastembed/examples/Supported_Models/) supports. It runs on ONNX Runtime, with no torch, and loads on the first statement that needs a vector, so the server starts without it. The first load downloads the model files into `~/.cache/fraise-mcp`, or `$XDG_CACHE_HOME/fraise-mcp` when `XDG_CACHE_HOME` is set, and later loads read them from there; `FASTEMBED_CACHE_PATH` names another directory. A graph's first vector fixes its dimension, so a graph keeps the model it was first written with.
|
|
55
|
+
|
|
56
|
+
## What gets embedded
|
|
57
|
+
|
|
58
|
+
A `remember` embeds its fact. A `recall` embeds its search terms, the words and phrases before its first clause. An `explain recall …` embeds the same terms as the recall it prefixes, which it ranks exactly alike. The server appends `vec:$v` and binds the vector beside the statement. A recall with no terms, where anchors alone seed the search, is sent as written, and so is a `describe recall`, which answers with the shape of what its recall reaches and would reach every fact holding a vector if it carried one, and any statement the server cannot read that far: the daemon checks every statement, and its error messages come back to the model as tool errors.
|
|
59
|
+
|
|
60
|
+
## What a recall answers
|
|
61
|
+
|
|
62
|
+
The `recall` tool answers with one line per fact, best first, and beside them with the daemon's response as structured content, under the same output schema as the built-in `fraise mcp` bridge. An `explain recall …` carries its `explain` blocks there, per fact and for the query, which the lines leave out. See [Explained recall](https://docs.getfraise.dev/docs/http-api/endpoints/explain).
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# fraise-mcp
|
|
2
|
+
|
|
3
|
+
An MCP server for a running [Fraise](https://github.com/FraiseHQ/fraise) daemon. It exposes two tools, `recall` and `remember`, each taking one FQL statement: `recall` runs every read, a recall, a `when` or a `describe` in front of a recall, and `remember` every write. It embeds every statement's text locally so retrieval is hybrid (text and vector) out of the box. The model writes plain FQL and never a vector.
|
|
4
|
+
|
|
5
|
+
<!-- mcp-name: io.github.FraiseHQ/fraise -->
|
|
6
|
+
|
|
7
|
+
## Run
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
uvx fraise-mcp
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Register it with your agent host:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
claude mcp add fraise -- uvx fraise-mcp
|
|
17
|
+
codex mcp add fraise -- uvx fraise-mcp
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
The server forwards to a daemon that runs separately (`brew services start fraise`, or `systemctl --user start fraise`), like a database behind a connection URL.
|
|
21
|
+
|
|
22
|
+
## Provenance
|
|
23
|
+
|
|
24
|
+
Every release is published to PyPI from this repository's release workflow, with a [PEP 740](https://peps.python.org/pep-0740/) attestation that PyPI shows as the file's provenance. A downloaded file verifies against the repository:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
uvx pypi-attestations verify pypi --repository https://github.com/FraiseHQ/fraise pypi:fraise_mcp-<version>-py3-none-any.whl
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Configure
|
|
31
|
+
|
|
32
|
+
Every setting is a flag, and each flag falls back to an environment variable:
|
|
33
|
+
|
|
34
|
+
| Flag | Environment | Default |
|
|
35
|
+
| --- | --- | --- |
|
|
36
|
+
| `--addr` | `FRAISE_ADDR` | `http://localhost:9876` |
|
|
37
|
+
| `--model` | `FRAISE_EMBEDDING_MODEL` | `BAAI/bge-small-en-v1.5` |
|
|
38
|
+
| `--no-vectors` | `FRAISE_NO_VECTORS=1` | vectors on |
|
|
39
|
+
|
|
40
|
+
The model is any text model [fastembed](https://qdrant.github.io/fastembed/examples/Supported_Models/) supports. It runs on ONNX Runtime, with no torch, and loads on the first statement that needs a vector, so the server starts without it. The first load downloads the model files into `~/.cache/fraise-mcp`, or `$XDG_CACHE_HOME/fraise-mcp` when `XDG_CACHE_HOME` is set, and later loads read them from there; `FASTEMBED_CACHE_PATH` names another directory. A graph's first vector fixes its dimension, so a graph keeps the model it was first written with.
|
|
41
|
+
|
|
42
|
+
## What gets embedded
|
|
43
|
+
|
|
44
|
+
A `remember` embeds its fact. A `recall` embeds its search terms, the words and phrases before its first clause. An `explain recall …` embeds the same terms as the recall it prefixes, which it ranks exactly alike. The server appends `vec:$v` and binds the vector beside the statement. A recall with no terms, where anchors alone seed the search, is sent as written, and so is a `describe recall`, which answers with the shape of what its recall reaches and would reach every fact holding a vector if it carried one, and any statement the server cannot read that far: the daemon checks every statement, and its error messages come back to the model as tool errors.
|
|
45
|
+
|
|
46
|
+
## What a recall answers
|
|
47
|
+
|
|
48
|
+
The `recall` tool answers with one line per fact, best first, and beside them with the daemon's response as structured content, under the same output schema as the built-in `fraise mcp` bridge. An `explain recall …` carries its `explain` blocks there, per fact and for the query, which the lines leave out. See [Explained recall](https://docs.getfraise.dev/docs/http-api/endpoints/explain).
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "fraise-mcp"
|
|
3
|
+
version = "0.1.1"
|
|
4
|
+
description = "Fraise MCP server: remember and recall over a running Fraise daemon, with vectors embedded locally"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"fraise-sdk[fastembed]>=0.4.1",
|
|
9
|
+
"mcp>=2.3.0,<3",
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
[[project.authors]]
|
|
13
|
+
name = "René-Jean Corneille"
|
|
14
|
+
email = "corneille.r.j@gmail.com"
|
|
15
|
+
|
|
16
|
+
[project.scripts]
|
|
17
|
+
fraise-mcp = "fraise_mcp.cli:main"
|
|
18
|
+
|
|
19
|
+
[project.optional-dependencies]
|
|
20
|
+
dev = [
|
|
21
|
+
"pytest>=9.1.1",
|
|
22
|
+
"pytest-cov>=7.1.0",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[tool.uv.sources.fraise-sdk]
|
|
26
|
+
workspace = true
|
|
27
|
+
|
|
28
|
+
[tool.pytest.ini_options]
|
|
29
|
+
minversion = "8.0"
|
|
30
|
+
addopts = [
|
|
31
|
+
"-ra",
|
|
32
|
+
"-q",
|
|
33
|
+
"--capture=no",
|
|
34
|
+
"-vvv",
|
|
35
|
+
"--import-mode=importlib",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[build-system]
|
|
39
|
+
requires = ["uv_build>=0.12.20,<0.13.0"]
|
|
40
|
+
build-backend = "uv_build"
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "fraise-mcp"
|
|
3
|
+
version = "0.1.1"
|
|
4
|
+
description = "Fraise MCP server: remember and recall over a running Fraise daemon, with vectors embedded locally"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "René-Jean Corneille", email = "corneille.r.j@gmail.com" }
|
|
8
|
+
]
|
|
9
|
+
requires-python = ">=3.12"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"fraise-sdk[fastembed]>=0.4.1", # x-release-please-version
|
|
12
|
+
"mcp>=2.3.0,<3",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[project.scripts]
|
|
16
|
+
fraise-mcp = "fraise_mcp.cli:main"
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
dev = [
|
|
20
|
+
"pytest>=9.1.1",
|
|
21
|
+
"pytest-cov>=7.1.0",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[tool.uv.sources]
|
|
25
|
+
fraise-sdk = { workspace = true }
|
|
26
|
+
|
|
27
|
+
[build-system]
|
|
28
|
+
requires = ["uv_build>=0.12.20,<0.13.0"]
|
|
29
|
+
build-backend = "uv_build"
|
|
30
|
+
|
|
31
|
+
# The suite's own pytest settings, so pytest's rootdir is this directory.
|
|
32
|
+
# --import-mode=importlib names each test module after its path from the
|
|
33
|
+
# rootdir. From the repository root that path starts with mcp/, and pytest
|
|
34
|
+
# would register this directory as the module `mcp`, hiding the mcp
|
|
35
|
+
# distribution the server is built on. From here it starts with src/.
|
|
36
|
+
[tool.pytest.ini_options]
|
|
37
|
+
minversion = "8.0"
|
|
38
|
+
addopts = ["-ra", "-q", "--capture=no", "-vvv", "--import-mode=importlib"]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
# Copyright (c) 2026 René-Jean Corneille
|
|
4
|
+
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
# in the Software without restriction, including without limitation the rights
|
|
8
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
# furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
# copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
# SOFTWARE.
|
|
22
|
+
"""Fraise MCP server: remember and recall over a running Fraise daemon.
|
|
23
|
+
|
|
24
|
+
The server embeds each statement's text locally and binds the vector, so the
|
|
25
|
+
model writes plain FQL and retrieval is hybrid out of the box. Run it with
|
|
26
|
+
``uvx fraise-mcp``.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
__all__ = ["build_server", "main"]
|
|
30
|
+
|
|
31
|
+
from fraise_mcp.cli import main
|
|
32
|
+
from fraise_mcp.server import build_server
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
# Copyright (c) 2026 René-Jean Corneille
|
|
4
|
+
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
# in the Software without restriction, including without limitation the rights
|
|
8
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
# furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
# copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
# SOFTWARE.
|
|
22
|
+
"""The ``fraise-mcp`` command: configure the server and serve it over stdio.
|
|
23
|
+
|
|
24
|
+
Every setting is a flag, and each flag falls back to an environment variable,
|
|
25
|
+
then to a default. A harness that launches the server as a subprocess can
|
|
26
|
+
configure it either way. Stdout belongs to the protocol once the server runs,
|
|
27
|
+
so nothing on this path prints to it.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import argparse
|
|
33
|
+
import os
|
|
34
|
+
import warnings
|
|
35
|
+
from collections.abc import Sequence
|
|
36
|
+
from importlib.metadata import version
|
|
37
|
+
|
|
38
|
+
from fraise_sdk.client import FraiseClient
|
|
39
|
+
from fraise_sdk.constants import DEFAULT_BASE_URL
|
|
40
|
+
from fraise_sdk.errors import FraiseWarning
|
|
41
|
+
from fraise_sdk.providers.fastembed import FastEmbedEmbedder
|
|
42
|
+
|
|
43
|
+
from fraise_mcp.server import build_server
|
|
44
|
+
|
|
45
|
+
ADDR_ENV = "FRAISE_ADDR"
|
|
46
|
+
MODEL_ENV = "FRAISE_EMBEDDING_MODEL"
|
|
47
|
+
NO_VECTORS_ENV = "FRAISE_NO_VECTORS"
|
|
48
|
+
CACHE_ENV = "FASTEMBED_CACHE_PATH"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _cache_dir() -> str:
|
|
52
|
+
"""Return the directory the embedding model's files are kept in.
|
|
53
|
+
|
|
54
|
+
fastembed's own default is the temp directory, which macOS sweeps every
|
|
55
|
+
night and Linux empties at reboot. The server never sends a statement
|
|
56
|
+
without its vector, so a swept model costs a silent download when online
|
|
57
|
+
and every write when offline. A per-user cache survives both, and
|
|
58
|
+
``FASTEMBED_CACHE_PATH`` still names the directory when it is set.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
``FASTEMBED_CACHE_PATH`` when set, else ``fraise-mcp`` under
|
|
62
|
+
``XDG_CACHE_HOME``, or under ``~/.cache`` without it.
|
|
63
|
+
"""
|
|
64
|
+
if path := os.environ.get(CACHE_ENV):
|
|
65
|
+
return path
|
|
66
|
+
base = os.environ.get("XDG_CACHE_HOME") or os.path.join(
|
|
67
|
+
os.path.expanduser("~"), ".cache"
|
|
68
|
+
)
|
|
69
|
+
return os.path.join(base, "fraise-mcp")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
|
73
|
+
"""Parse the command line, with each flag's environment variable as its default.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
argv: the arguments after the program name, ``None`` for
|
|
77
|
+
``sys.argv[1:]``.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
The settings: ``addr``, ``model`` (``None`` for the embedder's own
|
|
81
|
+
default) and ``no_vectors``.
|
|
82
|
+
"""
|
|
83
|
+
parser = argparse.ArgumentParser(
|
|
84
|
+
prog="fraise-mcp",
|
|
85
|
+
description="MCP server for a running Fraise daemon, over stdio.",
|
|
86
|
+
)
|
|
87
|
+
parser.add_argument(
|
|
88
|
+
"--addr",
|
|
89
|
+
default=os.environ.get(ADDR_ENV, DEFAULT_BASE_URL),
|
|
90
|
+
help=f"URL of the Fraise daemon (env {ADDR_ENV}, default {DEFAULT_BASE_URL})",
|
|
91
|
+
)
|
|
92
|
+
parser.add_argument(
|
|
93
|
+
"--model",
|
|
94
|
+
default=os.environ.get(MODEL_ENV) or None,
|
|
95
|
+
help=(
|
|
96
|
+
f"fastembed model the statements are embedded with (env {MODEL_ENV}, "
|
|
97
|
+
"default BAAI/bge-small-en-v1.5)"
|
|
98
|
+
),
|
|
99
|
+
)
|
|
100
|
+
parser.add_argument(
|
|
101
|
+
"--no-vectors",
|
|
102
|
+
action="store_true",
|
|
103
|
+
default=os.environ.get(NO_VECTORS_ENV, "").lower() in {"1", "true", "yes"},
|
|
104
|
+
help=f"send every statement on text alone (env {NO_VECTORS_ENV}=1)",
|
|
105
|
+
)
|
|
106
|
+
return parser.parse_args(argv)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def main(argv: Sequence[str] | None = None) -> None:
|
|
110
|
+
"""Run the server over stdio until the client disconnects.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
argv: the arguments after the program name, ``None`` for
|
|
114
|
+
``sys.argv[1:]``.
|
|
115
|
+
"""
|
|
116
|
+
args = parse_args(argv)
|
|
117
|
+
# The server renders the daemon's warnings into the tool result, where the
|
|
118
|
+
# model reads them. The SDK's own copy on stderr would only repeat them.
|
|
119
|
+
warnings.filterwarnings("ignore", category=FraiseWarning)
|
|
120
|
+
embedder = None
|
|
121
|
+
if not args.no_vectors:
|
|
122
|
+
cache_dir = _cache_dir()
|
|
123
|
+
embedder = (
|
|
124
|
+
FastEmbedEmbedder(args.model, cache_dir=cache_dir)
|
|
125
|
+
if args.model
|
|
126
|
+
else FastEmbedEmbedder(cache_dir=cache_dir)
|
|
127
|
+
)
|
|
128
|
+
with FraiseClient(args.addr) as client:
|
|
129
|
+
build_server(client, embedder, version=version("fraise-mcp")).run("stdio")
|
|
File without changes
|
|
@@ -0,0 +1,591 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
# Copyright (c) 2026 René-Jean Corneille
|
|
4
|
+
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
# in the Software without restriction, including without limitation the rights
|
|
8
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
# furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
# copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
# SOFTWARE.
|
|
22
|
+
"""The MCP server: the recall and remember tools over a Fraise client.
|
|
23
|
+
|
|
24
|
+
Each tool takes one FQL statement and sends it to the daemon through
|
|
25
|
+
:meth:`fraise_sdk.client.FraiseClient.query`. The daemon parses, plans and
|
|
26
|
+
runs it. When the statement takes a vector (see
|
|
27
|
+
:func:`fraise_mcp.statement.embedding_text`), the server encodes its text,
|
|
28
|
+
appends ``vec:$v`` and binds the vector out of band. So the tools carry
|
|
29
|
+
hybrid retrieval without the model ever writing a vector. The daemon's error
|
|
30
|
+
messages come back to the model as tool errors, so it can read them and
|
|
31
|
+
correct its statement.
|
|
32
|
+
|
|
33
|
+
A recall answers twice, as the built-in ``fraise mcp`` bridge does: rendered
|
|
34
|
+
to text for the model, and as structured content, the daemon's response under
|
|
35
|
+
the output schema below. The structured content is where the ``explain``
|
|
36
|
+
blocks of an ``explain recall`` ride, which the text leaves out.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
from datetime import datetime
|
|
42
|
+
from typing import Annotated, NotRequired, TypedDict
|
|
43
|
+
|
|
44
|
+
from fraise_sdk import models
|
|
45
|
+
from fraise_sdk.client import FraiseClient
|
|
46
|
+
from fraise_sdk.constants import VECTOR_PARAM
|
|
47
|
+
from fraise_sdk.errors import FraiseAPIError, FraiseError
|
|
48
|
+
from fraise_sdk.integrations.render import render_span
|
|
49
|
+
from fraise_sdk.models import RecallResult
|
|
50
|
+
from fraise_sdk.providers.base import EmbedderLike
|
|
51
|
+
from mcp.server.mcpserver import MCPServer
|
|
52
|
+
from mcp.server.mcpserver.exceptions import ToolError
|
|
53
|
+
from mcp.types import CallToolResult, TextContent
|
|
54
|
+
from pydantic import Field
|
|
55
|
+
|
|
56
|
+
from fraise_mcp.statement import embedding_text, with_vector
|
|
57
|
+
|
|
58
|
+
RECALL_DESCRIPTION = (
|
|
59
|
+
"Search the agent's long-term memory: run an FQL recall against the fraise "
|
|
60
|
+
"daemon and return the matching facts ranked by relevance and recency. "
|
|
61
|
+
"Anchors alone — topic:/entity: with no search terms — seed the search with "
|
|
62
|
+
"every fact filed under them, scored one unit per named anchor and decayed by "
|
|
63
|
+
"age, newest first under a single anchor: the way to see what is stored under "
|
|
64
|
+
"a topic before you know what to search for. A recall may also be written "
|
|
65
|
+
"explain recall …: it ranks exactly as the recall it prefixes, and its "
|
|
66
|
+
"structured result also says how the ranking was reached. This tool also "
|
|
67
|
+
"runs describe: put describe in front of a recall and it answers with the "
|
|
68
|
+
"shape of what the recall reaches instead of the facts — how many, when "
|
|
69
|
+
"they happened, and the topics and entities they are filed under, with how "
|
|
70
|
+
"many facts each files — and describe recall alone describes the whole "
|
|
71
|
+
"graph. When you do not know how memory is filed, describe recall first."
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
RECALL_QUERY = (
|
|
75
|
+
"A full FQL recall: search terms, then optional topic:/entity: anchors (beside "
|
|
76
|
+
"terms they lift the facts filed under them through the graph and filter "
|
|
77
|
+
"nothing, so the recall runs at depth:1 at least), top:N result cap, depth:0-2 "
|
|
78
|
+
"retrieval lane (the graph is searched only beside a topic:/entity:), "
|
|
79
|
+
"since:/until: time bounds (a date is quoted: since:'2026-01-15'). A bare term "
|
|
80
|
+
"or value is letters and digits only; quote anything else: 'e-mail', "
|
|
81
|
+
"topic:'machine-learning'. A search term that spells a keyword (top, since, "
|
|
82
|
+
"topic...) is quoted too: 'since'. Example: recall@2 barometer storm "
|
|
83
|
+
"topic:weather top:5 depth:1 since:7d. Anchors alone, with no terms, seed the "
|
|
84
|
+
"search with every fact filed under those topics/entities, scored one unit per "
|
|
85
|
+
"named anchor and decayed by age, so newest first under one anchor (depth: has "
|
|
86
|
+
"no effect). Example: recall@2 topic:weather top:20. describe in front of a "
|
|
87
|
+
"recall, which this tool runs as it runs a recall, answers with the catalogue "
|
|
88
|
+
"of what the recall reaches instead of its facts: how many facts, when they happened, and the topics and entities they "
|
|
89
|
+
"are filed under with each one's count. describe recall@2 describes the whole "
|
|
90
|
+
"graph, describe recall@2 topic:weather what is filed under an anchor and the "
|
|
91
|
+
"anchors filed beside it, and describe recall@2 barometer the anchors the "
|
|
92
|
+
"matching facts are filed under. Under describe, top:N caps the topics and the "
|
|
93
|
+
"entities listed, and since:/until: bound the facts counted."
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
REMEMBER_DESCRIPTION = (
|
|
97
|
+
"Store a self-contained fact in the agent's long-term memory: run an FQL "
|
|
98
|
+
"remember against the fraise daemon."
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
REMEMBER_QUERY = (
|
|
102
|
+
"A full FQL remember: the fact in single quotes, anchors as repeatable "
|
|
103
|
+
"topic:/entity: pairs, @N selecting the graph. An anchor value that is not "
|
|
104
|
+
"letters and digits only is quoted too: topic:'machine-learning'. Example: "
|
|
105
|
+
"remember@2 'the barometer falls before the storm' topic:weather entity:harbour"
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class Interval(TypedDict):
|
|
110
|
+
"""A span that holds start and excludes end; a single moment has the two equal."""
|
|
111
|
+
|
|
112
|
+
start: Annotated[datetime, Field(description="Where the span starts.")]
|
|
113
|
+
end: NotRequired[
|
|
114
|
+
Annotated[
|
|
115
|
+
datetime,
|
|
116
|
+
Field(
|
|
117
|
+
description="Where the span ends, itself excluded: equal to start "
|
|
118
|
+
"for a single moment, absent for a span that has not ended."
|
|
119
|
+
),
|
|
120
|
+
]
|
|
121
|
+
]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class Contribution(TypedDict):
|
|
125
|
+
"""One source's sighting of a fact, with that source's raw mass."""
|
|
126
|
+
|
|
127
|
+
source: Annotated[
|
|
128
|
+
str,
|
|
129
|
+
Field(
|
|
130
|
+
description="The source that saw the fact: text, vector, graph or anchor."
|
|
131
|
+
),
|
|
132
|
+
]
|
|
133
|
+
score: Annotated[
|
|
134
|
+
float,
|
|
135
|
+
Field(
|
|
136
|
+
description="That source's raw mass: the match mass for text, the "
|
|
137
|
+
"similarity for vector, the funding anchor's whole observed mass for "
|
|
138
|
+
"graph, one unit for anchor."
|
|
139
|
+
),
|
|
140
|
+
]
|
|
141
|
+
rank: Annotated[
|
|
142
|
+
int, Field(description="The fact's place in the source's ranking, 0 first.")
|
|
143
|
+
]
|
|
144
|
+
via: NotRequired[
|
|
145
|
+
Annotated[
|
|
146
|
+
str,
|
|
147
|
+
Field(
|
|
148
|
+
description="The topic or entity a graph or anchor sighting came "
|
|
149
|
+
"through."
|
|
150
|
+
),
|
|
151
|
+
]
|
|
152
|
+
]
|
|
153
|
+
degree: NotRequired[
|
|
154
|
+
Annotated[int, Field(description="How many facts are filed under that anchor.")]
|
|
155
|
+
]
|
|
156
|
+
count: Annotated[int, Field(description="How many seeds funded the sighting.")]
|
|
157
|
+
named: NotRequired[
|
|
158
|
+
Annotated[
|
|
159
|
+
bool,
|
|
160
|
+
Field(
|
|
161
|
+
description="True when the statement named the anchor, which then "
|
|
162
|
+
"passes its mass on without a fair share."
|
|
163
|
+
),
|
|
164
|
+
]
|
|
165
|
+
]
|
|
166
|
+
held: NotRequired[
|
|
167
|
+
Annotated[
|
|
168
|
+
float,
|
|
169
|
+
Field(
|
|
170
|
+
description="On a text sighting, the share of the query's "
|
|
171
|
+
"information the fact's own words hold."
|
|
172
|
+
),
|
|
173
|
+
]
|
|
174
|
+
]
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class HitExplain(TypedDict):
|
|
178
|
+
"""Present only on an explained recall: how this fact reached the ranking."""
|
|
179
|
+
|
|
180
|
+
seed: Annotated[
|
|
181
|
+
bool,
|
|
182
|
+
Field(
|
|
183
|
+
description="Whether the fact seeded the recall: a top text or vector "
|
|
184
|
+
"match, or a member of a named anchor when anchors alone seed. A fact "
|
|
185
|
+
"that is no seed and has graph contributions alone came in through an "
|
|
186
|
+
"anchor the seeds funded."
|
|
187
|
+
),
|
|
188
|
+
]
|
|
189
|
+
decay: Annotated[
|
|
190
|
+
float,
|
|
191
|
+
Field(
|
|
192
|
+
description="The recency factor the fact's relevance was scaled by to "
|
|
193
|
+
"give its score, in (0, 1]: it tells a fact ranked low for its age from "
|
|
194
|
+
"one ranked low for its match."
|
|
195
|
+
),
|
|
196
|
+
]
|
|
197
|
+
contributions: Annotated[
|
|
198
|
+
list[Contribution],
|
|
199
|
+
Field(
|
|
200
|
+
description="One entry per sighting of the fact, the ingredients its "
|
|
201
|
+
"score was folded from."
|
|
202
|
+
),
|
|
203
|
+
]
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class Hit(TypedDict):
|
|
207
|
+
"""A recalled fact: its value, its times, its score and, explained, its block."""
|
|
208
|
+
|
|
209
|
+
value: Annotated[str, Field(description="The remembered fact, exactly as stored.")]
|
|
210
|
+
timestamp: Annotated[datetime, Field(description="When the fact was written.")]
|
|
211
|
+
said: NotRequired[
|
|
212
|
+
Annotated[
|
|
213
|
+
datetime,
|
|
214
|
+
Field(
|
|
215
|
+
description="When the fact was said, as its remember gave it with "
|
|
216
|
+
"said:. Absent when it gave none: the fact was then said when it "
|
|
217
|
+
"was written."
|
|
218
|
+
),
|
|
219
|
+
]
|
|
220
|
+
]
|
|
221
|
+
occurred: NotRequired[
|
|
222
|
+
Annotated[
|
|
223
|
+
list[Interval],
|
|
224
|
+
Field(
|
|
225
|
+
description="Each span over which what the fact states happened, as "
|
|
226
|
+
"its remember gave them with occurred:. Absent when it gave none: "
|
|
227
|
+
"the fact then happened when it was said."
|
|
228
|
+
),
|
|
229
|
+
]
|
|
230
|
+
]
|
|
231
|
+
score: Annotated[
|
|
232
|
+
float,
|
|
233
|
+
Field(
|
|
234
|
+
description="Raw relevance in the scorer's own units: an ordering, not "
|
|
235
|
+
"a probability, with no upper bound. When anchors alone seed the search "
|
|
236
|
+
"it is one unit per named anchor the fact is filed under, decayed by age."
|
|
237
|
+
),
|
|
238
|
+
]
|
|
239
|
+
explain: NotRequired[HitExplain]
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
class NestedResults(TypedDict):
|
|
243
|
+
"""The results each when in a since:/until: bound answered, under that bound."""
|
|
244
|
+
|
|
245
|
+
since: NotRequired[Results]
|
|
246
|
+
until: NotRequired[Results]
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
class RecallExplain(TypedDict):
|
|
250
|
+
"""Present only on an explained recall: what the search measured about the query as a whole."""
|
|
251
|
+
|
|
252
|
+
background: Annotated[
|
|
253
|
+
float,
|
|
254
|
+
Field(
|
|
255
|
+
description="The background rate: seed mass per unit of anchor degree "
|
|
256
|
+
"over every anchor the round touched, 0 when no round ran."
|
|
257
|
+
),
|
|
258
|
+
]
|
|
259
|
+
admission: NotRequired[
|
|
260
|
+
Annotated[
|
|
261
|
+
dict[str, float],
|
|
262
|
+
Field(
|
|
263
|
+
description="Per depth, 1 and 2, the bar per unit of degree an "
|
|
264
|
+
"anchor the statement did not name had to exceed to pass its mass "
|
|
265
|
+
"on. Absent when no anchor round ran."
|
|
266
|
+
),
|
|
267
|
+
]
|
|
268
|
+
]
|
|
269
|
+
seeds: Annotated[
|
|
270
|
+
dict[str, int],
|
|
271
|
+
Field(
|
|
272
|
+
description="How many distinct facts each source (text, vector, anchor, "
|
|
273
|
+
"graph) seeded."
|
|
274
|
+
),
|
|
275
|
+
]
|
|
276
|
+
terms: Annotated[
|
|
277
|
+
list[str],
|
|
278
|
+
Field(
|
|
279
|
+
description="The query's terms as the text index read them, after "
|
|
280
|
+
"stop-word removal and stemming, including terms no fact holds."
|
|
281
|
+
),
|
|
282
|
+
]
|
|
283
|
+
timings: Annotated[
|
|
284
|
+
dict[str, int],
|
|
285
|
+
Field(description="Wall time each source took, in nanoseconds."),
|
|
286
|
+
]
|
|
287
|
+
when: NotRequired[
|
|
288
|
+
Annotated[
|
|
289
|
+
NestedResults,
|
|
290
|
+
Field(
|
|
291
|
+
description="Present only when a since:/until: bound holds a when: "
|
|
292
|
+
"the results that when answered, under the bound that holds it, "
|
|
293
|
+
"showing which fact the bound was read from and the time it gave."
|
|
294
|
+
),
|
|
295
|
+
]
|
|
296
|
+
]
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class CatalogueEntry(TypedDict):
|
|
300
|
+
"""One topic or entity the described facts are filed under."""
|
|
301
|
+
|
|
302
|
+
value: Annotated[str, Field(description="The topic or entity, as stored.")]
|
|
303
|
+
facts: Annotated[
|
|
304
|
+
int,
|
|
305
|
+
Field(
|
|
306
|
+
description="How many of the described facts are filed under it. Under "
|
|
307
|
+
"a describe of one anchor, the facts it shares with that anchor."
|
|
308
|
+
),
|
|
309
|
+
]
|
|
310
|
+
happened: NotRequired[
|
|
311
|
+
Annotated[
|
|
312
|
+
Interval,
|
|
313
|
+
Field(
|
|
314
|
+
description="From the earliest start to the latest end of what the "
|
|
315
|
+
"facts state took place; a fact given no occurred: happened when it "
|
|
316
|
+
"was said. No end when one of them has not ended."
|
|
317
|
+
),
|
|
318
|
+
]
|
|
319
|
+
]
|
|
320
|
+
said: NotRequired[
|
|
321
|
+
Annotated[
|
|
322
|
+
Interval,
|
|
323
|
+
Field(
|
|
324
|
+
description="From the first fact said to the last; a fact given no "
|
|
325
|
+
"said: was said when it was written."
|
|
326
|
+
),
|
|
327
|
+
]
|
|
328
|
+
]
|
|
329
|
+
written: NotRequired[
|
|
330
|
+
Annotated[
|
|
331
|
+
Interval, Field(description="From the first fact written to the last.")
|
|
332
|
+
]
|
|
333
|
+
]
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
class Catalogue(TypedDict):
|
|
337
|
+
"""What a describe answers with in place of hits: the shape of every fact its recall reaches."""
|
|
338
|
+
|
|
339
|
+
graph: Annotated[int, Field(description="The graph described.")]
|
|
340
|
+
scope: Annotated[
|
|
341
|
+
str,
|
|
342
|
+
Field(
|
|
343
|
+
description="The recall's body as the server read it, empty for the "
|
|
344
|
+
"whole graph."
|
|
345
|
+
),
|
|
346
|
+
]
|
|
347
|
+
facts: Annotated[
|
|
348
|
+
int,
|
|
349
|
+
Field(
|
|
350
|
+
description="How many facts the recall reaches: every candidate it would "
|
|
351
|
+
"rank, not the first top."
|
|
352
|
+
),
|
|
353
|
+
]
|
|
354
|
+
anchors: Annotated[
|
|
355
|
+
int,
|
|
356
|
+
Field(
|
|
357
|
+
description="How many topics and entities those facts are filed under, "
|
|
358
|
+
"before the lists are capped."
|
|
359
|
+
),
|
|
360
|
+
]
|
|
361
|
+
happened: NotRequired[
|
|
362
|
+
Annotated[
|
|
363
|
+
Interval,
|
|
364
|
+
Field(
|
|
365
|
+
description="From the earliest start to the latest end of what the "
|
|
366
|
+
"facts state took place; a fact given no occurred: happened when it "
|
|
367
|
+
"was said. No end when one of them has not ended."
|
|
368
|
+
),
|
|
369
|
+
]
|
|
370
|
+
]
|
|
371
|
+
said: NotRequired[
|
|
372
|
+
Annotated[
|
|
373
|
+
Interval,
|
|
374
|
+
Field(
|
|
375
|
+
description="From the first fact said to the last; a fact given no "
|
|
376
|
+
"said: was said when it was written."
|
|
377
|
+
),
|
|
378
|
+
]
|
|
379
|
+
]
|
|
380
|
+
written: NotRequired[
|
|
381
|
+
Annotated[
|
|
382
|
+
Interval, Field(description="From the first fact written to the last.")
|
|
383
|
+
]
|
|
384
|
+
]
|
|
385
|
+
topics: Annotated[
|
|
386
|
+
list[CatalogueEntry],
|
|
387
|
+
Field(
|
|
388
|
+
description="The topics the facts are filed under, the most filed first, "
|
|
389
|
+
"at most top: of them."
|
|
390
|
+
),
|
|
391
|
+
]
|
|
392
|
+
entities: Annotated[
|
|
393
|
+
list[CatalogueEntry],
|
|
394
|
+
Field(
|
|
395
|
+
description="The entities the facts are filed under, the most filed "
|
|
396
|
+
"first, at most top: of them."
|
|
397
|
+
),
|
|
398
|
+
]
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
class Results(TypedDict):
|
|
402
|
+
"""Ranked recall results, best first.
|
|
403
|
+
|
|
404
|
+
With anchors alone, each hit scores one unit per named anchor it is filed
|
|
405
|
+
under, decayed by age: newest first under a single anchor.
|
|
406
|
+
"""
|
|
407
|
+
|
|
408
|
+
count: Annotated[
|
|
409
|
+
int, Field(description="Number of hits returned, after the top: cap.")
|
|
410
|
+
]
|
|
411
|
+
hits: list[Hit]
|
|
412
|
+
start: NotRequired[
|
|
413
|
+
Annotated[
|
|
414
|
+
datetime,
|
|
415
|
+
Field(
|
|
416
|
+
description="Where the time a when answered with starts. Only a when "
|
|
417
|
+
"that matched a fact carries it."
|
|
418
|
+
),
|
|
419
|
+
]
|
|
420
|
+
]
|
|
421
|
+
end: NotRequired[
|
|
422
|
+
Annotated[
|
|
423
|
+
datetime,
|
|
424
|
+
Field(
|
|
425
|
+
description="Where that time ends, itself excluded: equal to start "
|
|
426
|
+
"for a single moment, absent for a time that has not ended."
|
|
427
|
+
),
|
|
428
|
+
]
|
|
429
|
+
]
|
|
430
|
+
explain: NotRequired[RecallExplain]
|
|
431
|
+
catalogue: NotRequired[Catalogue]
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
# The output schema mirrors the query endpoint's read response, as the
|
|
435
|
+
# built-in bridge's does, so a client reads the same structure from either
|
|
436
|
+
# server. Each class's docstring is the description the schema publishes.
|
|
437
|
+
class RecallOutput(TypedDict):
|
|
438
|
+
"""The daemon's answer to the recall, with any warnings it attached."""
|
|
439
|
+
|
|
440
|
+
results: Results
|
|
441
|
+
warnings: NotRequired[
|
|
442
|
+
Annotated[
|
|
443
|
+
list[str],
|
|
444
|
+
Field(
|
|
445
|
+
description="Warnings the server attached; the query still ran and "
|
|
446
|
+
"the results stand."
|
|
447
|
+
),
|
|
448
|
+
]
|
|
449
|
+
]
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def render(body: dict) -> str:
|
|
453
|
+
"""Render a query response for the model.
|
|
454
|
+
|
|
455
|
+
A write is acknowledged with a status token, so its confirmation is fixed
|
|
456
|
+
text. A recall is one line per hit, best first, relevance to three
|
|
457
|
+
decimals, in the voice of the SDK's framework tools. A recall can come back
|
|
458
|
+
with nothing in two ways. Either the graph holds nothing at all, which the
|
|
459
|
+
daemon answers 204 with no body, or a populated graph has no matching
|
|
460
|
+
fact. They read differently on purpose: the first calls for remembering
|
|
461
|
+
something, the second for asking differently. A describe answers with a
|
|
462
|
+
catalogue in place of hits, rendered as :func:`render_catalogue` renders
|
|
463
|
+
it. Warnings follow, one per line. The statement ran, and the model needs
|
|
464
|
+
them to fix its next one.
|
|
465
|
+
|
|
466
|
+
Args:
|
|
467
|
+
body: the decoded response body, ``{}`` for a 204.
|
|
468
|
+
|
|
469
|
+
Returns:
|
|
470
|
+
The text the model reads.
|
|
471
|
+
"""
|
|
472
|
+
catalogue = (body.get("results") or {}).get("catalogue")
|
|
473
|
+
if "status" in body:
|
|
474
|
+
lines = ["Remembered."]
|
|
475
|
+
elif catalogue is not None:
|
|
476
|
+
lines = render_catalogue(models.Catalogue.from_json(catalogue))
|
|
477
|
+
else:
|
|
478
|
+
result = RecallResult.from_json(
|
|
479
|
+
body.get("results") or {}, empty="results" not in body
|
|
480
|
+
)
|
|
481
|
+
lines = [f"- {hit.value} (relevance {hit.score:.3f})" for hit in result]
|
|
482
|
+
if not result and result.empty:
|
|
483
|
+
lines = [
|
|
484
|
+
"No stored facts matched: this graph is empty, nothing has been "
|
|
485
|
+
"remembered in it yet."
|
|
486
|
+
]
|
|
487
|
+
elif not result:
|
|
488
|
+
lines = ["No stored facts matched."]
|
|
489
|
+
lines += [f"warning: {warning}" for warning in body.get("warnings") or []]
|
|
490
|
+
return "\n".join(lines)
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def render_catalogue(catalogue: models.Catalogue) -> list[str]:
|
|
494
|
+
"""Render a describe's catalogue as the lines the model reads.
|
|
495
|
+
|
|
496
|
+
The first line spells the describe as the server read it, so the model can
|
|
497
|
+
widen or narrow it by editing what it reads, then gives how many facts the
|
|
498
|
+
recall reaches, the anchors they are filed under and when they happened.
|
|
499
|
+
The topics and then the entities follow, one per line in the order the
|
|
500
|
+
catalogue lists them, each with when its facts happened in front, as the
|
|
501
|
+
Go bridge renders them. A kind with no anchor says so, since a missing
|
|
502
|
+
section reads as a list cut off.
|
|
503
|
+
|
|
504
|
+
Args:
|
|
505
|
+
catalogue: the describe's answer.
|
|
506
|
+
|
|
507
|
+
Returns:
|
|
508
|
+
The lines, with no newline at their ends.
|
|
509
|
+
"""
|
|
510
|
+
statement = f"describe recall@{catalogue.graph}"
|
|
511
|
+
if catalogue.scope:
|
|
512
|
+
statement += f" {catalogue.scope}"
|
|
513
|
+
if not catalogue or catalogue.happened is None:
|
|
514
|
+
return [f"{statement}: no fact reached."]
|
|
515
|
+
facts = "1 fact" if catalogue.facts == 1 else f"{catalogue.facts} facts"
|
|
516
|
+
anchors = "1 anchor" if catalogue.anchors == 1 else f"{catalogue.anchors} anchors"
|
|
517
|
+
lines = [
|
|
518
|
+
f"{statement}: {facts} under {anchors}, happened {render_span(catalogue.happened)}"
|
|
519
|
+
]
|
|
520
|
+
for kind, entries in (
|
|
521
|
+
("topics", catalogue.topics),
|
|
522
|
+
("entities", catalogue.entities),
|
|
523
|
+
):
|
|
524
|
+
if not entries:
|
|
525
|
+
lines.append(f"{kind}: none")
|
|
526
|
+
continue
|
|
527
|
+
lines.append(f"{kind}:")
|
|
528
|
+
for entry in entries:
|
|
529
|
+
span = f"[{render_span(entry.happened)}] " if entry.happened else ""
|
|
530
|
+
count = "1 fact" if entry.facts == 1 else f"{entry.facts} facts"
|
|
531
|
+
lines.append(f"- {span}{entry.value}: {count}")
|
|
532
|
+
return lines
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def build_server(
|
|
536
|
+
client: FraiseClient, embedder: EmbedderLike | None, *, version: str = ""
|
|
537
|
+
) -> MCPServer:
|
|
538
|
+
"""Build the MCP server and register its recall and remember tools.
|
|
539
|
+
|
|
540
|
+
Args:
|
|
541
|
+
client: the client the statements are sent through.
|
|
542
|
+
embedder: what encodes a statement's text into its vector, or ``None``
|
|
543
|
+
to send every statement on text alone.
|
|
544
|
+
version: the version the server reports to its MCP client.
|
|
545
|
+
|
|
546
|
+
Returns:
|
|
547
|
+
The server, ready to run over stdio.
|
|
548
|
+
"""
|
|
549
|
+
server = MCPServer(name="fraise", version=version)
|
|
550
|
+
|
|
551
|
+
def run(statement: str) -> dict:
|
|
552
|
+
text = embedding_text(statement) if embedder is not None else None
|
|
553
|
+
parameters = None
|
|
554
|
+
if embedder is not None and text is not None:
|
|
555
|
+
try:
|
|
556
|
+
vector = [float(x) for x in embedder(text)]
|
|
557
|
+
except Exception as exc:
|
|
558
|
+
# The model loads, and downloads the first time, on this call.
|
|
559
|
+
# Whatever stops it is the operator's to fix, so it is said in
|
|
560
|
+
# words rather than as an anonymous crash.
|
|
561
|
+
raise ToolError(f"could not embed the statement: {exc}") from exc
|
|
562
|
+
parameters = {VECTOR_PARAM: vector}
|
|
563
|
+
statement = with_vector(statement)
|
|
564
|
+
try:
|
|
565
|
+
return client.query(statement, parameters=parameters)
|
|
566
|
+
except FraiseAPIError as exc:
|
|
567
|
+
raise ToolError(exc.message) from exc
|
|
568
|
+
except FraiseError as exc:
|
|
569
|
+
raise ToolError(str(exc)) from exc
|
|
570
|
+
|
|
571
|
+
def recall(
|
|
572
|
+
query: Annotated[str, Field(description=RECALL_QUERY)],
|
|
573
|
+
) -> Annotated[CallToolResult, RecallOutput]:
|
|
574
|
+
body = run(query)
|
|
575
|
+
# The schema requires results. A 204, the answer for a graph that holds
|
|
576
|
+
# nothing, has no body, and a write sent here answers with a status
|
|
577
|
+
# alone, so both read as the empty result: the text says which it was.
|
|
578
|
+
output: dict = {"results": body.get("results") or {"count": 0, "hits": []}}
|
|
579
|
+
if body.get("warnings"):
|
|
580
|
+
output["warnings"] = body["warnings"]
|
|
581
|
+
return CallToolResult(
|
|
582
|
+
content=[TextContent(type="text", text=render(body))],
|
|
583
|
+
structured_content=output,
|
|
584
|
+
)
|
|
585
|
+
|
|
586
|
+
def remember(query: Annotated[str, Field(description=REMEMBER_QUERY)]) -> str:
|
|
587
|
+
return render(run(query))
|
|
588
|
+
|
|
589
|
+
server.add_tool(recall, description=RECALL_DESCRIPTION, structured_output=True)
|
|
590
|
+
server.add_tool(remember, description=REMEMBER_DESCRIPTION, structured_output=False)
|
|
591
|
+
return server
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
# Copyright (c) 2026 René-Jean Corneille
|
|
4
|
+
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
# in the Software without restriction, including without limitation the rights
|
|
8
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
# furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
# copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
# SOFTWARE.
|
|
22
|
+
"""The text a statement's vector is encoded from, read off the statement itself.
|
|
23
|
+
|
|
24
|
+
The model writes plain FQL and never a ``vec:`` clause. The server takes a
|
|
25
|
+
vector only through one, bound out of band. So the server reads the statement
|
|
26
|
+
as written, and the bridge reads just enough of it to know what to encode: a
|
|
27
|
+
``remember``'s fact phrase, or a ``recall``'s terms. The grammar puts both
|
|
28
|
+
first, straight after the command. A recall's terms run until the first clause,
|
|
29
|
+
the first word glued to a ``:``. So the reader never needs the clause
|
|
30
|
+
vocabulary, and it never checks the statement. That stays the server's job.
|
|
31
|
+
|
|
32
|
+
Only statements the reader can follow take a vector. For anything else it
|
|
33
|
+
returns ``None``, and the statement is sent exactly as written. So whatever
|
|
34
|
+
the server says about it is about what the model wrote.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
from collections.abc import Iterator
|
|
40
|
+
from typing import Literal
|
|
41
|
+
|
|
42
|
+
from fraise_sdk.constants import KEYWORDS, VECTOR_PARAM
|
|
43
|
+
|
|
44
|
+
# The clause that binds the vector, appended to a statement that takes one.
|
|
45
|
+
VECTOR_CLAUSE = f"vec:${VECTOR_PARAM}"
|
|
46
|
+
|
|
47
|
+
# The prefixes the grammar allows in front of a recall. The recall behind one
|
|
48
|
+
# reads the same, so the reader steps over the prefix to find its terms.
|
|
49
|
+
_PREFIXES = frozenset({"explain", "describe"})
|
|
50
|
+
|
|
51
|
+
Kind = Literal["word", "phrase", "clause", "symbol"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _tokens(statement: str) -> Iterator[tuple[Kind, str]]:
|
|
55
|
+
"""Split ``statement`` into words, phrases, clause keys and symbols.
|
|
56
|
+
|
|
57
|
+
A word glued to a ``:`` is a clause key, and the ``:`` goes with it. A
|
|
58
|
+
phrase is unquoted, its doubled quotes read as one. Blanks separate
|
|
59
|
+
tokens and are dropped. A newline followed only by blanks and newlines
|
|
60
|
+
ends the statement, as it does for the parser.
|
|
61
|
+
|
|
62
|
+
Yields:
|
|
63
|
+
Each token's kind and text, in order.
|
|
64
|
+
|
|
65
|
+
Raises:
|
|
66
|
+
ValueError: at a newline another instruction follows, or at a phrase
|
|
67
|
+
with no closing quote.
|
|
68
|
+
"""
|
|
69
|
+
i, n = 0, len(statement)
|
|
70
|
+
while i < n:
|
|
71
|
+
ch = statement[i]
|
|
72
|
+
if ch in " \t\r":
|
|
73
|
+
i += 1
|
|
74
|
+
elif ch == "\n":
|
|
75
|
+
if statement[i:].strip(" \t\r\n"):
|
|
76
|
+
raise ValueError("more than one instruction")
|
|
77
|
+
return
|
|
78
|
+
elif ch == "'":
|
|
79
|
+
parts: list[str] = []
|
|
80
|
+
i += 1
|
|
81
|
+
while True:
|
|
82
|
+
end = statement.find("'", i)
|
|
83
|
+
if end < 0:
|
|
84
|
+
raise ValueError("unterminated phrase")
|
|
85
|
+
parts.append(statement[i:end])
|
|
86
|
+
if statement.startswith("''", end):
|
|
87
|
+
parts.append("'")
|
|
88
|
+
i = end + 2
|
|
89
|
+
continue
|
|
90
|
+
i = end + 1
|
|
91
|
+
break
|
|
92
|
+
yield "phrase", "".join(parts)
|
|
93
|
+
elif ch.isalpha() or ch.isdecimal():
|
|
94
|
+
start = i
|
|
95
|
+
while i < n and (statement[i].isalpha() or statement[i].isdecimal()):
|
|
96
|
+
i += 1
|
|
97
|
+
if i < n and statement[i] == ":":
|
|
98
|
+
i += 1
|
|
99
|
+
yield "clause", statement[start : i - 1].lower()
|
|
100
|
+
else:
|
|
101
|
+
yield "word", statement[start:i]
|
|
102
|
+
else:
|
|
103
|
+
i += 1
|
|
104
|
+
yield "symbol", ch
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def embedding_text(statement: str) -> str | None:
|
|
108
|
+
"""Return the text ``statement``'s vector is encoded from, or ``None``.
|
|
109
|
+
|
|
110
|
+
A ``remember`` encodes its fact phrase. A ``recall``, behind an
|
|
111
|
+
``explain`` prefix or not, encodes its terms, joined by a space, with each
|
|
112
|
+
phrase unquoted.
|
|
113
|
+
|
|
114
|
+
It returns ``None``, and so the statement takes no vector, when:
|
|
115
|
+
|
|
116
|
+
- the statement is any other command, or none;
|
|
117
|
+
- a recall has no terms. Anchors alone seed the search with every fact
|
|
118
|
+
filed under them, and a vector beside them would turn that into a
|
|
119
|
+
scored search;
|
|
120
|
+
- the recall stands behind ``describe``. A vector ranks every fact that
|
|
121
|
+
holds one, so a describe sent with one would reach each of them rather
|
|
122
|
+
than the facts its terms match;
|
|
123
|
+
- the statement binds a vector already;
|
|
124
|
+
- a term is a bare reserved word or a symbol, or the statement ends on a
|
|
125
|
+
bare reserved word or on a clause key with no value. Each is an error.
|
|
126
|
+
A vector would be wasted on it, and a clause appended where the server
|
|
127
|
+
reports it would change what the server says;
|
|
128
|
+
- the statement holds more than one instruction, or a phrase with no
|
|
129
|
+
closing quote.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
statement: one FQL statement, as the model wrote it.
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
The text to encode, or ``None`` when the statement takes no vector.
|
|
136
|
+
"""
|
|
137
|
+
try:
|
|
138
|
+
tokens = list(_tokens(statement))
|
|
139
|
+
except ValueError:
|
|
140
|
+
return None
|
|
141
|
+
if not tokens or ("clause", "vec") in tokens:
|
|
142
|
+
return None
|
|
143
|
+
kind, last = tokens[-1]
|
|
144
|
+
after_clause = len(tokens) > 1 and tokens[-2][0] == "clause"
|
|
145
|
+
if kind == "clause" or (
|
|
146
|
+
kind == "word" and last.lower() in KEYWORDS and not after_clause
|
|
147
|
+
):
|
|
148
|
+
return None
|
|
149
|
+
|
|
150
|
+
prefixed = tokens[0][0] == "word" and tokens[0][1] in _PREFIXES
|
|
151
|
+
if prefixed and tokens[0][1] == "describe":
|
|
152
|
+
return None
|
|
153
|
+
position = int(prefixed)
|
|
154
|
+
command = tokens[position] if position < len(tokens) else None
|
|
155
|
+
position += 1
|
|
156
|
+
# A graph selector, @N, is glued to the command. The server checks the
|
|
157
|
+
# glue, and the reader only steps over it.
|
|
158
|
+
if tokens[position : position + 1] == [("symbol", "@")]:
|
|
159
|
+
position += 2
|
|
160
|
+
rest = tokens[position:]
|
|
161
|
+
|
|
162
|
+
if command == ("word", "remember") and not prefixed:
|
|
163
|
+
return rest[0][1] if rest and rest[0][0] == "phrase" else None
|
|
164
|
+
if command != ("word", "recall"):
|
|
165
|
+
return None
|
|
166
|
+
terms: list[str] = []
|
|
167
|
+
for kind, value in rest:
|
|
168
|
+
if kind == "clause":
|
|
169
|
+
break
|
|
170
|
+
if kind == "symbol" or (kind == "word" and value.lower() in KEYWORDS):
|
|
171
|
+
return None
|
|
172
|
+
terms.append(value)
|
|
173
|
+
return " ".join(terms) or None
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def with_vector(statement: str) -> str:
|
|
177
|
+
"""Return ``statement`` with the vector clause appended.
|
|
178
|
+
|
|
179
|
+
A clause goes last, so every token the model wrote keeps its position, and
|
|
180
|
+
a recall's terms still come first.
|
|
181
|
+
"""
|
|
182
|
+
return f"{statement.rstrip()} {VECTOR_CLAUSE}"
|