BrainAPI is a knowledge graph–powered AI memory layer that transforms unstructured data into structured knowledge, enabling intelligent search, recommendations, and contextual memory for AI agents and applications.
Python ai-agentsai-memoryknowledge-graphknowledge-managementknowledge-representationreccomendation-system
feat(mcp): restricted to pat-only brains
Christiand51b7c090382
diff --git a/src/services/mcp/app.py b/src/services/mcp/app.pyindex d62cb58..d784c67 100644--- a/src/services/mcp/app.py+++ b/src/services/mcp/app.py@@ -2,17 +2,39 @@ from pathlib import Pathimport dotenvfrom starlette.applications import Starlette+from starlette.middleware import Middlewarefrom starlette.responses import JSONResponsefrom starlette.routing import Route_project_root = Path(__file__).resolve().parent.parent.parentdotenv.load_dotenv(_project_root / ".env")-from src.services.mcp.main import mcp+from src.services.mcp.main import auth_token_var, mcp_mcp_app = mcp.streamable_http_app()+class AuthContextMiddleware:+ def __init__(self, app):+ self.app = app++ async def __call__(self, scope, receive, send):+ if scope["type"] in ("http", "websocket"):+ headers = dict(scope.get("headers", []))+ token = None+ brainpat = headers.get(b"brainpat")+ if brainpat:+ token = brainpat.decode()+ else:+ raw = (headers.get(b"authorization") or b"").decode()+ if raw.startswith("Bearer: "):+ token = raw.removeprefix("Bearer: ").strip() or None+ elif raw.startswith("Bearer "):+ token = raw.removeprefix("Bearer ").strip() or None+ auth_token_var.set(token)+ await self.app(scope, receive, send)++async def _health(_request):return JSONResponse({"status": "ok"}, status_code=200)@@ -31,5 +53,6 @@ _custom_routes = []app = Starlette(routes=_custom_routes + list(_mcp_app.routes),+ middleware=[Middleware(AuthContextMiddleware)],lifespan=_mcp_app.router.lifespan_context,)diff --git a/src/services/mcp/main.py b/src/services/mcp/main.pyindex 8b0e7ec..060c2b3 100644--- a/src/services/mcp/main.py+++ b/src/services/mcp/main.py@@ -4,17 +4,21 @@ Project: mcpCreated Date: Tuesday February 10th 2026Author: Christian Nonis <[email protected]>------Last Modified: Tuesday February 10th 2026 8:30:11 pm+Last Modified: Sunday February 22nd 2026 5:21:48 pmModified By: Christian Nonis <[email protected]>-----"""+from contextvars import ContextVarfrom typing import Anyfrom mcp.server import FastMCPfrom pydantic import BaseModelfrom src.lib.neo4j.client import _neo4j_clientfrom src.services.data.main import data_adapterfrom src.services.kg_agent.main import graph_adapter+from src.services.mcp.utils import guard_brainpat++auth_token_var: ContextVar[str | None] = ContextVar("auth_token", default=None)mcp = FastMCP("brainapi-mcp", stateless_http=True, host="0.0.0.0")@@ -50,6 +54,8 @@ def search_memory(db_query: str, brain_id: str) -> Any:- brain_id: str: the brain to search in."""try:+ if not guard_brainpat(auth_token_var.get(), brain_id):+ return "Unauthorized"return graph_adapter.execute_operation(db_query, brain_id)except Exception as e:return f"Error executing graph operation: {e}"@@ -60,5 +66,14 @@ def list_brains() -> list[str]:"""This tool lists all the brains/memory stores available"""+ brain_key = guard_brainpat(auth_token_var.get())+ if not brain_key:+ return "Unauthorized"++ # Returns only the brain which has the pat+ if type(brain_key) == str:+ return [brain_key]++ # Gets all the brainsbrains = data_adapter.get_brains_list()return [brain.name_key for brain in brains]diff --git a/src/services/mcp/utils.py b/src/services/mcp/utils.pynew file mode 100644index 0000000..2904fa7--- /dev/null+++ b/src/services/mcp/utils.py@@ -0,0 +1,33 @@+"""+File: /utils.py+Project: mcp+Created Date: Saturday March 14th 2026+Author: Christian Nonis <[email protected]>+-----+Last Modified: Saturday March 14th 2026 3:56:40 pm+Modified By: Christian Nonis <[email protected]>+-----+"""++from src.config import config+from src.services.data.main import data_adapter+++def guard_brainpat(pat: str = None, target_brain: str = None) -> bool | str:+ """+ Ensure the brainpat guarantees the access to the requested resource.++ If the BrainPAT is not matching any brain, it will try to match with the systempat,+ if the systempat is not matching, it will raise an auth error.+ """+ if pat == config.brainpat_token:+ return True++ brains = data_adapter.get_brains_list()+ for brain in brains:+ if brain.pat == pat:+ if target_brain and brain.name_key != target_brain:+ return False+ return brain.name_key++ return False