@maru

Fastify v6 and MCP — Building a Local-First Agent Backend
The unnecessary token waste and latency issues caused by disconnected agents unable to share state are known as the 'Agent Island Tax.' Conventional state synchronization via centralized databases or external APIs introduces high latency, limiting real-time collaboration between agents in local environments. To address this, the Model Context Protocol (MCP) and local-first peer-to-peer (P2P) agent networks are emerging as efficient alternatives.
In this post, we explore how to leverage Fastify v6's registered scope plugin lifecycle to build a secure agent backend architecture that operates independently without resource conflicts. We provide a clear architectural guide for combining decentralized local memory and real-time tool integration on top of a high-performance server framework.
Combining Local-First Agents with P2P Memory
Existing multi-agent systems often waste precious tokens as each agent operates in isolation, requiring redundant input of the same context. kioku-mesh, an open-source P2P shared memory technology, solves this by synchronizing state and development context between multiple agents locally in real-time, without the need for an external database.
kioku-mesh features a distributed structure combining Zenoh, a decentralized communication middleware, and local SQLite. Zenoh's key-value store and the RocksDB backend act as the source of truth, while each device's SQLite functions as a cache and derived view for high-speed retrieval. As a result, even if agents record memories simultaneously while offline, conflicts are resolved in a decentralized manner without a central server, based on Hybrid Logical Clocks (HLC).
There are some version-specific precautions for production operations. kioku-mesh changed its visibility control policy starting from v0.8, so if you are using legacy data, you must migrate to the latest structure using the kioku-mesh migrate-visibility --from legacy --to mesh command. Additionally, environment variables that previously used the MESH_MEM_ prefix have been fully standardized to KIOKU_MESH_ starting from v1.0.0, so your deployment pipeline's environment variable specifications will also need to be updated.
Agent Encapsulation via Fastify v6 Registered Scope Decorators
Fastify v6 introduces new registered scope decorator types, moving away from the traditional global type declaration merging method. In previous versions, adding decorators often polluted the global namespace, leading to type interference between individual plugins in monorepos or multi-agent environments. Now, specific Model Context Protocol servers, SQLite storage, and P2P node instances can be safely encapsulated within isolated plugin scopes.
This structure is implemented via the fastify-plugin helper function provided by the createPlugin package. Since type inference occurs only within the registered scope without polluting types globally across plugin boundaries, multiple agent infrastructures can be run safely within a single process without collisions.
(Next editorial step instruction: Please add a TypeScript file comparison example here that contrasts legacy code using global namespace declarations with new code using registered scope type inference with createPlugin.)
Implementing MCP Using Mastra and Plugin Lifecycles
By utilizing the Fastify server adapter in Mastra v1.0.0, you can integrate agent workflows and MCP functionality into your Fastify application in a perfectly isolated manner. Mastra's observational memory uses background agents to compress conversation content into lightweight text logs in real-time, significantly reducing token costs.
In particular, combining it with a Zod-based memory extractor allows for the extraction of structured data directly during asynchronous stream processing by leveraging existing context and prompt cache, without additional model calls. Below is the core code structure for encapsulating these observational memories and extractors within the Fastify v6 plugin lifecycle.
import { FastifyPluginAsync } from 'fastify';
import { Mastra } from '@mastra/core';
import { Memory, Extractor } from '@mastra/memory';
import { z } from 'zod';
export const agentPlugin: FastifyPluginAsync = async (fastify) => {
const memory = new Memory({
observationalMemory: true,
extractors: [
new Extractor({
schema: z.object({ theme: z.enum(['light', 'dark']) }),
instructions: '사용자의 UI 테마 선호도를 실시간으로 감지하세요.',
}),
],
});
fastify.decorate('mastra', new Mastra({ memory }));
};Mastra instances bound via decorators can be easily propagated to other microservices or agent nodes. Through this, MCP servers coupled with local SQLite storage can safely persist conversation history and structured session state within each routing context without global pollution.
Moving Toward Secure and Observable Agent Infrastructure
Granular, request-level distributed tracing is essential for stable operation of distributed P2P agent environments. Since @opentelemetry/instrumentation-fastify is now deprecated, you must migrate to the official plugin, @fastify/otel. This official plugin exposes request.openTelemetry() within the request scope, seamlessly connecting LLM calls or tool executions to the root HTTP distributed trace.
Applying the latest OpenTelemetry GenAI semantic conventions at this stage can improve the consistency of collected information. Instead of direct prompt logging, it is recommended to design systems that use serialized JSON message attributes to prevent sensitive data leaks. Additionally, for backend routes with high traffic, a useful tip is to set @fastify/otel when registering instrumentHooks: false to minimize the creation of unnecessary lifecycle spans.
Beyond observability, the integrity of local sandboxes and the security of the Fastify ecosystem itself are crucial. Dependencies must be patched regularly to ensure there are no internal library flaws, such as recently resolved schema bypass vulnerabilities (CVE-2026-18504) or proxy spoofing vulnerabilities. The more closely an MCP environment is integrated with local file and network resources, the more essential it is to combine isolated sandbox security measures with dependency audits to ensure robust infrastructure stability.
Reference Links