"""KCIEP VFS adapter for an official MCP ClientSession. Caller owns transport/OAuth. Receipts come from the server, never local synthesis. No automatic write replay; reconcile stable request IDs before explicit resumption. """ import asyncio import hashlib import json import re from dataclasses import dataclass from mcp import ClientSession class CommitUncertain(RuntimeError): """The mutation must be reconciled before another write is attempted.""" @dataclass(frozen=True) class VFSObject: id: str digest: str size_bytes: int request_id: str | None = None class KeddehVFS: def __init__(self, session: ClientSession): self.session = session self._lock = asyncio.Lock() self._requests = {} self._uncertain = set() async def _call(self, name, args): result = await self.session.call_tool(name, args) if result.isError: raise RuntimeError('Keddeh VFS tool failed: ' + name) if len(result.content) != 1 or result.content[0].type != 'text': raise ValueError('Unexpected MCP result shape') value = json.loads(result.content[0].text) if type(value) is not dict: raise ValueError('MCP result must be an object') return value @staticmethod def _args(request_id, name, content, domain_id): if type(request_id) is not str or not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', request_id): raise ValueError('Stable request ID required') if type(name) is not str or not name.strip(): raise ValueError('Object name required') if type(content) is not str or len(content.encode('utf-8')) > 100000: raise ValueError('UTF-8 content exceeds server contract') if type(domain_id) is not str or not re.fullmatch(r'[a-z0-9-]+', domain_id): raise ValueError('Canonical domain required') return {'requestId': request_id, 'name': name.strip(), 'content': content, 'domainId': domain_id} @staticmethod def _bind(value, args): if type(value) is not dict: raise ValueError('Committed result missing') data = args['content'].encode('utf-8') obj = value.get('object') if (value.get('ok') is not True or value.get('requestId') != args['requestId'] or type(obj) is not dict or type(obj.get('id')) is not str or type(obj.get('sizeBytes')) is not int or obj.get('digest') != hashlib.sha256(data).hexdigest() or obj['sizeBytes'] != len(data)): raise ValueError('Commit response does not bind submitted bytes and request') # Bind the runtime's retained carrier address, not just equal content bytes. stable = hashlib.sha256(('vfs:' + args['requestId']).encode()).hexdigest() safe_name = re.sub(r'[^a-zA-Z0-9._-]+', '-', args['name'])[:80] suffix = '/KEDDEH-SYSTEMS/' + args['domainId'] + '/' + stable + '/' + safe_name if (not obj['id'].endswith('_' + stable) or ('_' + args['domainId'].upper() + '_VFS_') not in obj['id'] or type(obj.get('objectKey')) is not str or not obj['objectKey'].endswith(suffix)): raise ValueError('Commit response does not bind retained address') return VFSObject(obj['id'], obj['digest'], obj['sizeBytes'], args['requestId']) async def put(self, *, request_id: str, name: str, content: str, domain_id: str = 'vfs', resume_prepared: bool = False) -> VFSObject: args = self._args(request_id, name, content, domain_id) async with self._lock: prior = self._requests.get(request_id) if prior is not None and prior != args: raise ValueError('Request ID payload/context conflict') self._requests[request_id] = args status = await self.commit_status(request_id) if status['state'] == 'VFS_COMMITTED': obj = self._bind(status.get('result'), args) self._uncertain.discard(request_id) return obj if status['state'] == 'VFS_PREPARED': if not resume_prepared: raise CommitUncertain('Prepared commit requires explicit resumption') elif status['state'] != 'NOT_FOUND': raise CommitUncertain('Unresolved commit state: ' + status['state']) elif request_id in self._uncertain: raise CommitUncertain('Lost response unresolved; no automatic replay') self._uncertain.add(request_id) value = await self._call('vfs_put', args) obj = self._bind(value, args) self._uncertain.discard(request_id) return obj async def read(self, obj: VFSObject) -> str: value = await self._call('vfs_read', {'id': obj.id}) if type(value.get('content')) is not str: raise ValueError('Read response content missing') data = value['content'].encode('utf-8') if (value.get('verified') is not True or value.get('id') != obj.id or type(value.get('sizeBytes')) is not int or value['sizeBytes'] != obj.size_bytes or value.get('digest') != obj.digest or len(data) != obj.size_bytes or hashlib.sha256(data).hexdigest() != obj.digest): raise ValueError('Retained content integrity mismatch') return value['content'] async def commit_status(self, request_id: str): if type(request_id) is not str or not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', request_id): raise ValueError('Stable request ID required') value = await self._call('vfs_commit_status', {'requestId': request_id}) if value.get('requestId') != request_id or type(value.get('state')) is not str: raise ValueError('Commit status request binding mismatch') return value