Buckets:

download
raw
10.7 kB
"""
Obscura MCP Server – Encrypted secret vault for AI-assisted development.
Stores API keys, tokens, and secrets in an Argon2-encrypted JSON file.
Provides MCP tools for CRUD operations and a run subcommand that spawns
a child process with decrypted secrets in its environment.
"""
import json
import os
import shlex
import subprocess
import sys
import tempfile
import uuid
from pathlib import Path
try:
from argon2.low_level import hash_secret_raw, Type
HAS_ARGON2 = True
except ImportError:
HAS_ARGON2 = False
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from mcp.server.fastmcp import FastMCP
VAULT_DIR = Path(os.environ.get("OBSCURA_VAULT_DIR", Path.home() / ".obscura"))
VAULT_FILE = VAULT_DIR / "vault.json"
PASSPHRASE_FILE = VAULT_DIR / ".passphrase"
mcp = FastMCP("obscura", instructions="Encrypted secret vault for API keys, tokens, and credentials.")
def _ensure_vault_dir():
VAULT_DIR.mkdir(parents=True, exist_ok=True)
def _derive_key(passphrase: str, salt: bytes) -> bytes:
if not HAS_ARGON2:
raise RuntimeError("argon2-cffi not installed. Run: pip install argon2-cffi")
return hash_secret_raw(
secret=passphrase.encode(),
salt=salt,
time_cost=3,
memory_cost=65536,
parallelism=4,
hash_len=32,
type=Type.ID,
)
def _encrypt(plaintext: str, passphrase: str, salt: bytes | None = None) -> tuple[bytes, bytes]:
key = _derive_key(passphrase, salt or os.urandom(16))
nonce = os.urandom(12)
ciphertext = AESGCM(key).encrypt(nonce, plaintext.encode(), None)
return nonce + ciphertext, key
def _decrypt(data: bytes, passphrase: str) -> str:
salt = data[:16]
nonce = data[16:28]
ciphertext = data[28:]
key = _derive_key(passphrase, salt)
return AESGCM(key).decrypt(nonce, ciphertext, None).decode()
def _load_vault(passphrase: str) -> dict[str, str]:
if not VAULT_FILE.exists():
return {}
raw = VAULT_FILE.read_bytes()
if raw.startswith(b"{"):
return json.loads(raw)
try:
decrypted = _decrypt(raw, passphrase)
return json.loads(decrypted)
except Exception:
raise ValueError("Invalid passphrase or corrupted vault")
def _save_vault(data: dict[str, str], passphrase: str):
_ensure_vault_dir()
plaintext = json.dumps(data, indent=2)
salt = os.urandom(16)
encrypted, _ = _encrypt(plaintext, passphrase, salt)
VAULT_FILE.write_bytes(salt + encrypted)
def _get_passphrase() -> str:
if PASSPHRASE_FILE.exists():
return PASSPHRASE_FILE.read_text().strip()
pw = os.environ.get("OBSCURA_PASSPHRASE")
if pw:
return pw
raise ValueError(
"No passphrase available. Set OBSCURA_PASSPHRASE env, create ~/.obscura/.passphrase, "
"or use 'init_vault' tool to set one."
)
def _scope_path(scope: str) -> Path:
path = Path.cwd() if scope == "project" else Path.home()
return path / ".obscura"
@mcp.resource("obscura://info")
async def vault_info() -> str:
"""Vault status and metadata."""
_ensure_vault_dir()
exists = VAULT_FILE.exists()
pw_set = PASSPHRASE_FILE.exists() or bool(os.environ.get("OBSCURA_PASSPHRASE"))
return json.dumps(
{
"vault_path": str(VAULT_FILE),
"vault_exists": exists,
"passphrase_configured": pw_set,
"argon2_available": HAS_ARGON2,
}
)
@mcp.resource("obscura://secrets")
async def list_secrets_resource() -> str:
"""List all stored secret names."""
try:
pw = _get_passphrase()
vault = _load_vault(pw)
return json.dumps({"secrets": list(vault.keys()), "count": len(vault)})
except ValueError as e:
return json.dumps({"error": str(e), "secrets": []})
@mcp.tool()
def init_vault(passphrase: str = "") -> str:
"""Initialize or rekey the vault with a passphrase.
If passphrase is empty, generates one and prints it.
Save the passphrase to ~/.obscura/.passphrase for automatic use.
"""
_ensure_vault_dir()
if not passphrase:
import string
import random
chars = string.ascii_letters + string.digits + "!@#$%^&*"
passphrase = "".join(random.choices(chars, k=24))
try:
old_pw = _get_passphrase() if VAULT_FILE.exists() else None
vault = _load_vault(old_pw) if old_pw and VAULT_FILE.exists() else {}
except ValueError:
vault = {}
_save_vault(vault, passphrase)
PASSPHRASE_FILE.write_text(passphrase)
return json.dumps(
{
"status": "ok",
"vault": str(VAULT_FILE),
"passphrase": passphrase,
"existing_secrets": len(vault),
}
)
@mcp.tool()
def store_secret(key: str, value: str) -> str:
"""Store a secret in the vault."""
try:
pw = _get_passphrase()
vault = _load_vault(pw)
vault[key] = value
_save_vault(vault, pw)
return json.dumps({"status": "ok", "key": key})
except Exception as e:
return json.dumps({"status": "error", "error": str(e)})
@mcp.tool()
def get_secret(key: str) -> str:
"""Retrieve a secret from the vault."""
try:
pw = _get_passphrase()
vault = _load_vault(pw)
if key not in vault:
return json.dumps({"status": "error", "error": f"Secret '{key}' not found"})
return json.dumps({"status": "ok", "key": key, "value": vault[key]})
except Exception as e:
return json.dumps({"status": "error", "error": str(e)})
@mcp.tool()
def list_secrets(pattern: str = "") -> str:
"""List secret names, optionally filtered by glob pattern."""
try:
pw = _get_passphrase()
vault = _load_vault(pw)
keys = list(vault.keys())
if pattern:
keys = [k for k in keys if pattern.lower() in k.lower()]
return json.dumps({"status": "ok", "secrets": keys, "count": len(keys)})
except Exception as e:
return json.dumps({"status": "error", "error": str(e)})
@mcp.tool()
def delete_secret(key: str) -> str:
"""Delete a secret from the vault."""
try:
pw = _get_passphrase()
vault = _load_vault(pw)
if key not in vault:
return json.dumps({"status": "error", "error": f"Secret '{key}' not found"})
removed = vault.pop(key)
_save_vault(vault, pw)
return json.dumps({"status": "ok", "key": key})
except Exception as e:
return json.dumps({"status": "error", "error": str(e)})
@mcp.tool()
def copy_secret(key: str, from_global: bool = True) -> str:
"""Copy a secret between project and global scope."""
try:
pw = _get_passphrase()
vault_global = _load_vault(pw)
src_scope = "global" if from_global else "project"
dst_scope = "project" if from_global else "global"
src_vault = vault_global
dst_file = _scope_path("project") / "vault.json"
if from_global:
if key not in src_vault:
return json.dumps({"status": "error", "error": f"Secret '{key}' not in global vault"})
dst_path = _scope_path("project")
else:
dst_path = _scope_path("global")
try:
dst_raw = dst_path.read_bytes() if dst_path.exists() else b"{}"
src_vault = json.loads(_decrypt(dst_raw, pw)) if dst_raw.startswith(b"\x00") else json.loads(dst_raw)
except Exception:
src_vault = {}
if key not in vault_global:
return json.dumps({"status": "error", "error": f"Secret '{key}' not in project vault"})
src_vault = vault_global
value = src_vault[key]
store_secret(key, value)
return json.dumps({"status": "ok", "key": key, "from": src_scope, "to": dst_scope})
except Exception as e:
return json.dumps({"status": "error", "error": str(e)})
@mcp.tool()
def run_command(command: str, keys: list[str] | None = None) -> str:
"""Run a command with selected (or all) secrets injected as environment variables.
The vault stays locked until this call, is decrypted only for the
duration of the child process, and re-locked immediately after.
"""
try:
pw = _get_passphrase()
vault = _load_vault(pw)
env = os.environ.copy()
selected = keys or list(vault.keys())
for k in selected:
if k in vault:
env[k.upper()] = vault[k]
result = subprocess.run(
shlex.split(command),
capture_output=True,
text=True,
timeout=30,
env=env,
)
return json.dumps(
{
"status": "ok",
"stdout": result.stdout,
"stderr": result.stderr,
"returncode": result.returncode,
}
)
except subprocess.TimeoutExpired:
return json.dumps({"status": "error", "error": "Command timed out"})
except Exception as e:
return json.dumps({"status": "error", "error": str(e)})
@mcp.tool()
def export_dotenv(file_path: str = ".env") -> str:
"""Export all secrets to a dotenv file (plaintext – use with care)."""
try:
pw = _get_passphrase()
vault = _load_vault(pw)
lines = [f'{k}="{v}"' for k, v in vault.items()]
Path(file_path).write_text("\n".join(lines) + "\n")
return json.dumps({"status": "ok", "file": file_path, "secrets": len(lines)})
except Exception as e:
return json.dumps({"status": "error", "error": str(e)})
def _parse_dotenv(text: str) -> dict[str, str]:
result = {}
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
continue
key, _, val = line.partition("=")
key = key.strip()
val = val.strip().strip("\"'")
result[key] = val
return result
@mcp.tool()
def import_dotenv(file_path: str = ".env") -> str:
"""Import secrets from a dotenv file into the vault."""
try:
pw = _get_passphrase()
vault = _load_vault(pw)
with open(file_path) as f:
parsed = _parse_dotenv(f.read())
imported = 0
for k, v in parsed.items():
vault[k.upper()] = v
imported += 1
_save_vault(vault, pw)
return json.dumps({"status": "ok", "imported": imported})
except Exception as e:
return json.dumps({"status": "error", "error": str(e)})
def main():
_ensure_vault_dir()
mcp.run()
if __name__ == "__main__":
main()

Xet Storage Details

Size:
10.7 kB
·
Xet hash:
e60c1c9837ca14f91d1c1837d7ed4a71b9bfc9eea2df14956d1f3205b3f46b85

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.