Building Multi-Agent Context Sharing Mechanisms in Semantica: Architecture and Implementation Guide
Semantica enables autonomous agents to share collective knowledge through a unified context graph and vector store, using the DecisionContext class to persist decisions and the ContextRetriever to expand queries with knowledge graph relationships.
The semantica-agi/semantica framework provides a Python-based infrastructure for building multi-agent systems where context sharing functions as a core architectural primitive rather than an external integration. By combining high-dimensional vector embeddings with graph-based relationship traversal, Semantica allows autonomous agents to record their decisions, discover relevant historical context, and build upon the collective knowledge of the entire agent swarm.
Core Architecture Components
The framework implements a layered architecture that separates storage concerns from retrieval logic, enabling pluggable backends while maintaining a consistent API for agent developers.
DecisionContext – The Central Coordination Layer
At the heart of Semantica's multi-agent system lies the DecisionContext class, implemented in [semantica/context/decision_context.py](https://github.com/semantica-agi/semantica/blob/main/semantica/context/decision_context.py). This class serves as the primary interface for agents to record decisions and retrieve shared context. It coordinates between the vector store for semantic similarity and the knowledge graph for relational traversal. The constructor accepts vector_store and graph_store parameters, allowing developers to inject specific backend implementations such as PgVectorStore or KnowledgeGraph instances.
ContextRetriever – Graph-Expanded Vector Search
The ContextRetriever, defined in [semantica/context/context_retriever.py](https://github.com/semantica-agi/semantica/blob/main/semantica/context/context_retriever.py), implements the mechanism for expanding a query beyond simple vector similarity. When an agent requests context, the retriever first identifies relevant entities in the knowledge graph, computes paths and centrality metrics, then performs a weighted similarity search that blends raw embedding similarity with graph-derived relevance scores. This ensures agents receive not just semantically similar results, but contextually connected decisions from the broader agent network.
Storage Backends and the MCP Protocol
Semantica abstracts persistence through two main interfaces: the Vector Store for embeddings ([semantica/vector_store/pgvector_store.py](https://github.com/semantica-agi/semantica/blob/main/semantica/vector_store/pgvector_store.py)) and the KnowledgeGraph for entity relationships ([semantica/integrations/agno/knowledge_graph.py](https://github.com/semantica-agi/semantica/blob/main/semantica/integrations/agno/knowledge_graph.py)). The MCP (Message Control Protocol) Server in [semantica/mcp/server.py](https://github.com/semantica-agi/semantica/blob/main/semantica/mcp/server.py) provides the RPC layer enabling agents to register, publish context updates, and retrieve shared state over HTTP/WebSocket, while [semantica/mcp/session.py](https://github.com/semantica-agi/semantica/blob/main/semantica/mcp/session.py) manages atomic transactions to ensure consistency.
Context Flow: Recording and Retrieval
Understanding the data flow between agents requires examining how Semantica handles write operations via record_decision() and read operations through retrieve().
Recording Decisions with Metadata and Embeddings
When an agent records a decision, the DecisionContext.record_decision() method executes a three-phase commit:
- Embedding Generation: The decision payload (text and metadata) is converted to high-dimensional vectors using the configured embedding pipeline.
- Vector Persistence: The embedding is stored via the vector store's
store()method, typically implemented inPgVectorStorefor production deployments. - Graph Registration: Corresponding nodes and edges (e.g., "Decision → Entity") are created in the knowledge graph through the
KnowledgeGraphAPI, recording provenance and relationships.
Retrieving Shared Context with Hops and Weighting
Agents retrieve collective knowledge through ContextRetriever.retrieve(), which accepts parameters including max_results, max_hops, and context_weight. The retrieval process:
- Extracts the latest knowledge graph sub-graph relevant to the query using path-finding and community detection algorithms.
- Expands the seed entity set by up to N hops (controlled by
max_hops) to capture indirectly related decisions. - Performs a weighted similarity search where
context_weightdetermines the blend between graph relevance and embedding similarity.
Implementation Example
The following example demonstrates initializing the storage backends, creating a shared decision context, recording agent decisions, and retrieving context expanded through the knowledge graph.
# Initialise the core stores
from semantica.context import DecisionContext
from semantica.vector_store.pgvector_store import PgVectorStore
from semantica.integrations.agno.knowledge_graph import KnowledgeGraph
vs = PgVectorStore(dsn="postgresql://user:pwd@localhost/semantica")
kg = KnowledgeGraph(endpoint="http://localhost:7200/repositories/semantica")
# Create a decision context (shared by all agents)
ctx = DecisionContext(vector_store=vs, graph_store=kg)
# Record a decision with rich metadata
decision_id = ctx.record_decision(
title="Approve loan",
description="Customer meets all credit criteria.",
metadata={"customer_id": "C1234", "amount": 15000},
)
# Retrieve the most relevant past decisions, expanded by KG context
retriever = ctx.get_retriever()
results = retriever.retrieve(
query="loan approval for high‑value customers",
max_results=5,
max_hops=2, # expand through up to 2 KG hops
context_weight=0.2, # blend graph relevance with embedding similarity
)
for r in results:
print(r.title, r.metadata["customer_id"])
For multi-agent synchronization, deploy the MCP server and client:
# Run the MCP server (typically in a separate process)
from semantica.mcp.server import start_server
start_server(host="0.0.0.0", port=8000)
# Agents connect and sync their contexts
from semantica.mcp.session import MCPClient
client = MCPClient("http://localhost:8000")
client.publish_context(ctx) # push local updates
shared = client.fetch_context() # pull the global view
Background maintenance of graph metrics runs via [semantica/worker.py](https://github.com/semantica-agi/semantica/blob/main/semantica/worker.py), which periodically recomputes centrality and community structures to keep the knowledge graph optimized for retrieval. Detailed architectural rationale is documented in [ARCHITECTURE.md](https://github.com/semantica-agi/semantica/blob/main/ARCHITECTURE.md).
Summary
- The DecisionContext class in
semantica/context/decision_context.pyprovides the primary API for agents to record decisions and access shared context through a unified interface. - ContextRetriever enables knowledge-graph-driven query expansion via
max_hopsandcontext_weightparameters, blending vector similarity with relational relevance. - Storage backends are pluggable: use
PgVectorStorefor vector persistence andKnowledgeGraphfor entity relationship management. - The MCP server architecture facilitates real-time context synchronization across distributed agents while maintaining atomic consistency guarantees.
- All components support constructor-level injection, allowing developers to swap embedding models, vector stores, or disable graph expansion without modifying core logic.
Frequently Asked Questions
How does ContextRetriever blend graph topology with vector similarity?
The ContextRetriever.retrieve() method implements a two-stage ranking system. First, it queries the knowledge graph to identify entities within max_hops of the query subject, calculating graph centrality and path strength. Then it performs a vector similarity search against the expanded entity set, applying the context_weight parameter (typically 0.0 to 1.0) to interpolate between the graph relevance score and the cosine similarity of embeddings. This hybrid approach ensures agents receive results that are both semantically similar and contextually grounded in the provenance network.
What storage backends does Semantica support for multi-agent context?
Semantica abstracts storage through interface classes. For vector storage, the framework provides PgVectorStore in semantica/vector_store/pgvector_store.py, which implements batch insertion and async indexing over PostgreSQL with the pgVector extension. For knowledge graph storage, KnowledgeGraph in semantica/integrations/agno/knowledge_graph.py supports RDF-compliant backends including GraphDB and Amazon Neptune. Both backends accept configuration via the DecisionContext constructor, allowing drop-in replacement of storage technologies without changing agent code.
How does the MCP server ensure atomic context updates across agents?
The MCP protocol implementation in semantica/mcp/session.py manages session lifecycles using atomic commit and rollback mechanisms. When an agent publishes context via MCPClient.publish_context(), the session manager coordinates with the underlying storage transactions to ensure that vector store updates and knowledge graph writes either complete together or fail together. This prevents partial updates where an embedding might persist without its corresponding graph relationships, maintaining consistency in multi-agent environments where multiple agents may write concurrently.
Can I disable knowledge graph expansion if I only need vector similarity?
Yes. The ContextRetriever supports configuration through the DecisionContext constructor arguments. By setting max_hops=0 or initializing the retriever with a null graph store, the system bypasses the knowledge graph expansion phase entirely. In this mode, retrieve() performs pure vector similarity search against the PgVectorStore backend. This configuration is useful for lightweight deployments or when the relational structure between decisions is not relevant to the agent's task, though it sacrifices the provenance tracking and multi-hop reasoning capabilities that the knowledge graph provides.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →