Skip to main content
Glama

ad4m_write_memory

Write signed semantic links (source-predicate-target) to a persistent Perspective, auto-optimizing memory every 10 writes for efficient cross-session context.

Instructions

Write a signed LinkExpression (source → predicate → target) to a Perspective. Auto-optimizes the graph every 10 writes across all terminals.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
perspective_uuidYesTarget Perspective UUID
sourceYesSource URI — e.g. 'agent://session/2026-03-22'
predicateNoPredicate URI — e.g. 'ad4m://knows' (default: ad4m://relates)
targetYesTarget URI or literal — e.g. 'literal://decision text'

Implementation Reference

  • src/index.ts:304-324 (registration)
    Registration of the ad4m_write_memory tool with the MCP server, including its schema (perspective_uuid, source, predicate, target) and the handler that calls the AD4M GraphQL perspectiveAddLink mutation.
    server.tool("ad4m_write_memory",
      "Write a signed LinkExpression (source → predicate → target) to a Perspective. Auto-optimizes the graph every 10 writes across all terminals.",
      {
        perspective_uuid: z.string().describe("Target Perspective UUID"),
        source:           z.string().describe("Source URI — e.g. 'agent://session/2026-03-22'"),
        predicate:        z.string().optional().describe("Predicate URI — e.g. 'ad4m://knows' (default: ad4m://relates)"),
        target:           z.string().describe("Target URI or literal — e.g. 'literal://decision text'"),
      },
      async ({ perspective_uuid, source, predicate = "ad4m://relates", target }) => {
        const data = await gql(
          `mutation M($uuid: String!, $link: LinkInput!) {
             perspectiveAddLink(uuid: $uuid, link: $link) {
               author timestamp data { source predicate target }
             }
           }`,
          { uuid: perspective_uuid, link: { source, predicate, target } }
        );
        tickWriteCounter(perspective_uuid).catch(() => {});
        return ok(data.perspectiveAddLink);
      }
    );
  • Zod input schema for ad4m_write_memory: perspective_uuid (string), source (string), predicate (optional string, default ad4m://relates), target (string).
    {
      perspective_uuid: z.string().describe("Target Perspective UUID"),
      source:           z.string().describe("Source URI — e.g. 'agent://session/2026-03-22'"),
      predicate:        z.string().optional().describe("Predicate URI — e.g. 'ad4m://knows' (default: ad4m://relates)"),
      target:           z.string().describe("Target URI or literal — e.g. 'literal://decision text'"),
    },
  • The gql() helper function used by the handler to send GraphQL mutations to the AD4M executor.
    async function gql(query: string, variables: Record<string, unknown> = {}): Promise<GqlResult> {
      const resp = await fetch(AD4M_GQL, {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({ query, variables }),
        signal:  AbortSignal.timeout(10_000),
      });
      if (!resp.ok) throw new Error(`AD4M HTTP ${resp.status}: ${await resp.text()}`);
      const json = await resp.json() as { data?: GqlResult; errors?: { message: string }[] };
      if (json.errors?.length) {
        const msg = json.errors[0].message;
        if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed")) {
          throw new Error("AD4M executor not reachable. Start it with: ad4m serve --port 4000");
        }
        if (msg.includes("Unauthorized") || msg.includes("not unlocked")) {
          throw new Error(`Agent is locked. Unlock with:\ncurl -X POST ${AD4M_GQL} -H 'Content-Type: application/json' -d '{"query":"mutation { agentUnlock(passphrase: \\"YOUR_PASSPHRASE\\") { isUnlocked } }"}'`);
        }
        throw new Error(msg);
      }
      return json.data ?? {};
    }
  • The tickWriteCounter() helper called after each write to auto-optimize the perspective every 10 writes.
    async function tickWriteCounter(uuid: string): Promise<void> {
      const { link: old, count } = await getSharedCount(uuid);
      if (old) await removeLink(uuid, old).catch(() => {});
      const next = count + 1;
      if (next >= OPTIMIZE_THRESHOLD) {
        optimizePerspective(uuid, false).catch(() => {});
      } else {
        await gql(
          `mutation A($uuid: String!, $link: LinkInput!) {
             perspectiveAddLink(uuid: $uuid, link: $link) { author timestamp }
           }`,
          { uuid, link: { source: CTR_SOURCE, predicate: CTR_PRED, target: `literal://${next}` } }
        ).catch(() => {});
      }
    }
  • The handler function for ad4m_write_memory: executes the GraphQL perspectiveAddLink mutation and triggers the write counter.
    async ({ perspective_uuid, source, predicate = "ad4m://relates", target }) => {
      const data = await gql(
        `mutation M($uuid: String!, $link: LinkInput!) {
           perspectiveAddLink(uuid: $uuid, link: $link) {
             author timestamp data { source predicate target }
           }
         }`,
        { uuid: perspective_uuid, link: { source, predicate, target } }
      );
      tickWriteCounter(perspective_uuid).catch(() => {});
      return ok(data.perspectiveAddLink);
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden. It discloses the auto-optimization side effect but omits details on mutation (e.g., destructiveness, idempotency, authorization requirements). No annotation contradiction.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences, no wasted words, front-loaded with the core action. Efficient and clear.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Adequate for a write tool with moderate complexity (4 params, no nested objects). Missing return value description, error handling, and further context on the optimization behavior, but not critical given sibling tools like ad4m_recall for reading.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, but the description adds semantic context by explaining parameters as parts of a LinkExpression (source, predicate, target) and providing example URIs, going beyond the schema's minimal descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states 'Write a signed LinkExpression (source → predicate → target) to a Perspective,' specifying the action and resource. It also mentions auto-optimization, distinguishing it from siblings like ad4m_delete_memory.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies the tool is for writing link expressions to perspectives but provides no explicit guidance on when to use it vs alternatives like relay_write, nor any prerequisites or conditions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/thefranceway/mcp-ad4m'

If you have feedback or need assistance with the MCP directory API, please join our Discord server