Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Each directory is its own Go module with annotated Go files. Run one with `gomcp
| [`files`](files) | read-only directory browser: resource template, two tools, path traversal protection | HTTP or stdio |
| [`todo`](todo) | todo list in a JSON file: Setup and Teardown, tools, a prompt, a resource | HTTP or stdio |
| [`fetch`](fetch) | `fetch_url` with an allowlist, size limit and timeout, `ToolError` | HTTP or stdio |
| [`remember`](remember) | knowledge base in SQLite: `remember`, `recall`, `forget`; semantic search with an embedding endpoint (Ollama, OpenAI, ...), BM25 without | HTTP or stdio |
| [`features`](features) | every feature once (auth, tasks, sampling, elicitation, ...), see its README | HTTP or stdio |
| [`esm`](esm) | ticket desk: Entra authentication with scopes per role, confirmation before every change, a state machine in a service on top of a repository, tests at every level, see its README | HTTP (auth), stdio for local tries |

Expand Down
68 changes: 68 additions & 0 deletions examples/remember/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# remember

A knowledge base the model fills and queries, stored in SQLite. No authentication, meant to run locally for one person.

- `remember`: stores a fact (text plus optional tags).
- `recall`: finds the facts closest to a question, best first, with a score. `min_score` drops weak hits.
- `forget`: deletes a fact by id.

## Two ways to search

| | Configured | How `recall` ranks | Finds `vehicle` for "my car is red" |
| --- | --- | --- | --- |
| semantic | `REMEMBER_EMBED_URL` set | cosine similarity of embedding vectors | yes |
| lexical | nothing set | BM25 over stemmed words, prefixes and typos (trigrams) | no |

The embedding endpoint is anything OpenAI compatible (`POST {url}/embeddings`): OpenAI, Ollama, LM Studio, vLLM, LiteLLM.
Each fact's vector is stored next to it in SQLite (a `float32` BLOB) together with the model that made it.
Vectors of different models are not comparable, so at start every fact with a missing or foreign vector is embedded
again. That makes two things automatic: turning embeddings on for an existing database, and changing the model.
An unreachable endpoint stops the start, and `remember` fails instead of storing a fact it cannot find later.

## Configuration

| Variable | Meaning |
| --- | --- |
| `REMEMBER_DB` | SQLite file, default `./remember.db` |
| `REMEMBER_EMBED_URL` | base URL, e.g. `http://localhost:11434/v1` for Ollama. Empty: lexical search |
| `REMEMBER_EMBED_MODEL` | embedding model, required with the URL, e.g. `nomic-embed-text` |
| `REMEMBER_EMBED_KEY` | API key, if the endpoint needs one |

Note the text of a fact leaves the machine when the endpoint is a hosted one. Use a local Ollama for private notes.

### Try it with Ollama

Ollama serves the OpenAI API under `http://localhost:11434/v1`. Pull an embedding model first; chat models also answer
`/embeddings`, but slowly and with poor results.

```sh
ollama pull nomic-embed-text # about 270 MB

REMEMBER_DB=$HOME/remember.db \
REMEMBER_EMBED_URL=http://localhost:11434/v1 REMEMBER_EMBED_MODEL=nomic-embed-text \
gomcp serve ./examples/remember
```

Without the two `REMEMBER_EMBED_*` variables the server uses lexical search and needs no setup: `gomcp serve ./examples/remember`.
A model that is not pulled stops the start with the endpoint's error.

Client config for stdio (build once, `gomcp stdio` compiles on every start; the first build of the SQLite driver takes a while):

```sh
gomcp build ./examples/remember ./bin/remember
```

```json
{
"mcpServers": {
"remember": {
"command": "/absolute/path/to/bin/remember",
"args": ["--stdio"],
"env": { "REMEMBER_DB": "/Users/steven/remember.db", "REMEMBER_EMBED_URL": "http://localhost:11434/v1", "REMEMBER_EMBED_MODEL": "nomic-embed-text" }
}
}
}
```

Every `recall` reads all rows and compares against every vector: fine for thousands of facts. Beyond tens of thousands, use
an index (sqlite-vec, an ANN library).
105 changes: 105 additions & 0 deletions examples/remember/embed.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package api

import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"strings"
"time"
)

// An embedder talks to any OpenAI compatible POST {url}/embeddings: OpenAI, Ollama
// (http://localhost:11434/v1), LM Studio, vLLM, LiteLLM. The text becomes a vector;
// texts about the same thing end up close together, whatever their words.
type embedder struct {
url, model, key string
client *http.Client
}

// embed returns the vector for text.
func (e *embedder) embed(ctx context.Context, text string) ([]float32, error) {
body, _ := json.Marshal(map[string]any{"model": e.model, "input": text})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimSuffix(e.url, "/")+"/embeddings", bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
if e.key != "" {
req.Header.Set("Authorization", "Bearer "+e.key)
}
resp, err := e.client.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
data, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("embedding endpoint answered %s", resp.Status)
}
var out struct {
Data []struct {
Embedding []float32 `json:"embedding"`
} `json:"data"`
}
if err := json.Unmarshal(data, &out); err != nil || len(out.Data) != 1 || len(out.Data[0].Embedding) == 0 {
return nil, errors.New("embedding endpoint sent no vector")
}
return out.Data[0].Embedding, nil
}

// newEmbedder reads REMEMBER_EMBED_URL, REMEMBER_EMBED_MODEL and REMEMBER_EMBED_KEY
// (optional). Without a URL it returns nil and the memory falls back to lexical search.
func newEmbedder(getenv func(string) string) (*embedder, error) {
url := getenv("REMEMBER_EMBED_URL")
if url == "" {
return nil, nil
}
model := getenv("REMEMBER_EMBED_MODEL")
if model == "" {
return nil, errors.New("REMEMBER_EMBED_URL is set, so REMEMBER_EMBED_MODEL must be set too")
}
return &embedder{url: url, model: model, key: getenv("REMEMBER_EMBED_KEY"), client: &http.Client{Timeout: 30 * time.Second}}, nil
}

// cosine similarity in [-1,1]; 0 for vectors of different size or length zero.
func cosine(a, b []float32) float64 {
if len(a) != len(b) {
return 0
}
var dot, na, nb float64
for i := range a {
dot += float64(a[i]) * float64(b[i])
na += float64(a[i]) * float64(a[i])
nb += float64(b[i]) * float64(b[i])
}
if na == 0 || nb == 0 {
return 0
}
return dot / (math.Sqrt(na) * math.Sqrt(nb))
}

// encode and decode store a vector as little endian float32 in a BLOB.
func encode(v []float32) []byte {
out := make([]byte, 4*len(v))
for i, f := range v {
binary.LittleEndian.PutUint32(out[4*i:], math.Float32bits(f))
}
return out
}

func decode(b []byte) []float32 {
out := make([]float32, len(b)/4)
for i := range out {
out[i] = math.Float32frombits(binary.LittleEndian.Uint32(b[4*i:]))
}
return out
}
20 changes: 20 additions & 0 deletions examples/remember/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module github.com/StevenCyb/example_remember

go 1.26.2

require github.com/StevenCyb/GoMCP v0.0.0

require (
github.com/dustin/go-humanize v1.1.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sys v0.49.0 // indirect
modernc.org/libc v1.80.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
modernc.org/sqlite v1.64.0 // indirect
)

replace github.com/StevenCyb/GoMCP => ../..
20 changes: 20 additions & 0 deletions examples/remember/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
modernc.org/libc v1.80.1 h1:ejn7HtTV3GknNKbklqWQ1nvUrfX8mTxs1D+xp/JQwy4=
modernc.org/libc v1.80.1/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.64.0 h1:xCoLcRc2g33gLkmaRrcsJLitr4TRMQGGb3H4HYs3mbM=
modernc.org/sqlite v1.64.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE=
Loading
Loading