#!/usr/bin/env python3
"""Deterministic agent-security design calculations; local-only, no credentials or network."""
import argparse,csv,json,math,os
from pathlib import Path
os.environ.setdefault('MPLCONFIGDIR','/tmp/tensorfact-matplotlib')
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch,FancyArrowPatch
ROOT=Path(__file__).resolve().parents[1];parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output',type=Path);args=parser.parse_args()
OUT=args.output or (ROOT/'public/research-assets/ai-agent-mcp-security' if (ROOT/'app/data/research.json').is_file() else Path.cwd()/'agent-security-results');OUT.mkdir(parents=True,exist_ok=True)
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'svg.fonttype':'none','svg.hashsalt':'agent-security-v1','axes.spines.top':False,'axes.spines.right':False,'axes.labelcolor':'#244556','text.color':'#1d4050'})
C=['#244f69','#548b78','#b88346']
def save(fig,name):
 if name in ['workflow-exposure', 'revocation-window', 'zero-failure-bound']:
  fig.text(.02,-.025,'CALCULATED MODEL / ASSUMED INPUTS — NOT EMPIRICAL MEASUREMENTS',fontsize=8,color='#4f6d61')
 fig.savefig(OUT/(name+'.svg'),bbox_inches='tight',metadata={'Date':None});fig.savefig(OUT/(name+'.png'),bbox_inches='tight',dpi=200);plt.close(fig)
 path=OUT/(name+'.svg');path.write_text('\n'.join(line.rstrip() for line in path.read_text().replace("'DejaVu Sans'", "'DejaVu Sans', Arial, sans-serif").splitlines())+'\n')
def csvout(name,headers,rows):
 with (OUT/name).open('w',newline='') as f:w=csv.writer(f,lineterminator='\n');w.writerow(headers);w.writerows(rows)
n=np.arange(1,201);probabilities=[.0001,.001,.01];curves=[-np.expm1(n*np.log1p(-p)) for p in probabilities]
fig,ax=plt.subplots(figsize=(9,4.8),layout='constrained')
for i,p in enumerate(probabilities):ax.plot(n,curves[i]*100,color=C[i],lw=2,label=f'Assumed per-call probability p = {p:g}')
ax.set(xlabel='Tool-decision opportunities in one workflow',ylabel='Probability of at least one event (%)',title='IID probability identity under chosen inputs');ax.legend(fontsize=9);ax.grid(alpha=.15);save(fig,'workflow-exposure')
csvout('workflow-exposure.csv',['decision_count','any_event_p0001','any_event_p001','any_event_p01'],zip(n,*curves))
ttl=np.geomspace(30,3600,301);d=60.;c=30.;online=np.minimum(ttl,d+c)
fig,ax=plt.subplots(figsize=(9,4.8),layout='constrained');ax.loglog(ttl/60,ttl/60,color=C[0],lw=2,label='Expiry-only bound');ax.loglog(ttl/60,online/60,color=C[1],lw=2,label='Assumed detection 60 s + propagation/cache 30 s');ax.set(xlabel='Maximum token lifetime (minutes)',ylabel='Stale-authorization window bound (minutes)',title='Conditional expiry and revocation budgets');ax.legend(fontsize=8);ax.grid(alpha=.15,which='both');save(fig,'revocation-window')
csvout('revocation-window.csv',['token_lifetime_seconds','expiry_only_bound_seconds','revocation_bound_seconds'],zip(ttl,ttl,online))
trials=np.unique(np.rint(np.geomspace(10,100000,400)).astype(int));alpha=.05;upper=-np.expm1(np.log(alpha)/trials)
fig,ax=plt.subplots(figsize=(9,4.8),layout='constrained');ax.loglog(trials,upper*100,color=C[0],lw=2);ax.axhline(.1,color=C[2],ls='--',label='Illustrative upper target: 0.1%');ax.set(xlabel='Independent representative trials with zero failures',ylabel='One-sided 95% upper failure probability (%)',title='Zero observed failures is a bounded statement');ax.legend(fontsize=9);ax.grid(alpha=.15,which='both');save(fig,'zero-failure-bound')
csvout('zero-failure-bound.csv',['independent_trial_count','upper_failure_probability_95pct'],zip(trials,upper))
def canvas(title,subtitle):
 fig,ax=plt.subplots(figsize=(12,6.8));fig.patch.set_facecolor('#f7f9f5');fig.subplots_adjust(left=.02,right=.98,bottom=.02,top=.97);ax.set(xlim=(0,1),ylim=(0,1));ax.axis('off');ax.text(.02,.98,title,fontsize=17,fontweight='bold',va='top');ax.text(.02,.91,subtitle,fontsize=10,color='#5a7769',va='top');return fig,ax
def box(ax,x,y,w,h,title,body,fill='#ffffff'):
 ax.add_patch(FancyBboxPatch((x,y),w,h,boxstyle='round,pad=0.008,rounding_size=0.01',fc=fill,ec='#bbcec0',lw=1));ax.text(x+.014,y+h-.035,title,fontsize=11,fontweight='bold',va='top');ax.text(x+.014,y+h-.087,body,fontsize=9.5,va='top',linespacing=1.7,color='#547263')
def arrow(ax,a,b):ax.add_patch(FancyArrowPatch(a,b,arrowstyle='-|>',mutation_scale=12,lw=1.5,color='#6b8877',shrinkA=4,shrinkB=4))
fig,ax=canvas('AGENT–TOOL TRUST BOUNDARIES','Proposed system design / Model proposals are distinct from identity and execution authority.')
for x,title,body in [(.02,'User + task','Declared objective\nTenant + delegation'),(.27,'Agent planner','Untrusted proposals\nNo production credential'),(.52,'Policy enforcer','Actor, target, action\nApproval + resource state'),(.77,'Resource server','MCP audience validation\nScoped resource access')]:box(ax,x,.59,.21,.23,title,body,fill='#e7f0e4' if x==.52 else '#ffffff')
for x,title,body in [(.02,'External content','Documents + messages\nData, not authority'),(.27,'Result envelope','Source + sensitivity\nUntrusted tool output'),(.52,'Independent audit','Request + policy version\nOutcome + evidence'),(.77,'Identity authority','Issuer trust + token scope\nFreshness + revocation')]:box(ax,x,.18,.21,.23,title,body)
for x in [.23,.48,.73]:arrow(ax,(x,.705),(x+.04,.705))
arrow(ax,(.23,.295),(.27,.295));arrow(ax,(.375,.41),(.375,.59));arrow(ax,(.625,.59),(.625,.41));arrow(ax,(.875,.41),(.875,.59))
ax.plot([.98,.995,.995,.375],[.705,.705,.11,.11],color='#6b8877',lw=1.2);arrow(ax,(.375,.11),(.375,.18))
ax.text(.025,.07,'Protocol authentication establishes a caller. Application policy must still authorize the exact operation.',fontsize=10,color='#5d786a');save(fig,'trust-boundaries')
fig,ax=canvas('APPROVAL MUST BIND TO THE EXECUTED ACTION','Proposed application control / The request is checked again at the side-effect boundary.')
for x,title,body in [(.03,'1 / Prepare + approve','Canonical target and arguments\nTool version + state precondition\nActor, tenant and expiry'),(.37,'2 / Compare + authorize','Recompute the action binding\nCheck current policy and state\nReject changed or stale requests'),(.71,'3 / Execute + verify','Scoped service-side execution\nIdempotency and result status\nPostcondition + audit receipt')]:box(ax,x,.37,.26,.36,title,body,fill='#e7f0e4' if x==.37 else '#ffffff')
arrow(ax,(.29,.55),(.37,.55));arrow(ax,(.63,.55),(.71,.55));ax.text(.035,.23,'A changed target, tool definition, tenant, sensitive argument or required state invalidates the earlier approval.',fontsize=10,color='#5d786a');ax.text(.035,.15,'A digest supports binding; it does not replace identity, authorization or a trustworthy approval interface.',fontsize=10,color='#5d786a');save(fig,'action-binding')
result={'workflow_50_p001':-math.expm1(50*math.log1p(-.001)),'workflow_200_p001':-math.expm1(200*math.log1p(-.001)),'workflow_50_p001_gate_escape001':-math.expm1(50*math.log1p(-.001*.01)),'token900_expiry_bound_seconds':900,'token900_revocation_bound_seconds':90,'zero_failure_upper_n100':-math.expm1(math.log(.05)/100),'zero_failure_upper_n1000':-math.expm1(math.log(.05)/1000),'zero_failure_upper_n10000':-math.expm1(math.log(.05)/10000),'trials_for_upper_below_0p001':math.ceil(math.log(.05)/math.log1p(-.001))}
manifest={'model_version':'1.1','inputs':{'per_call_probabilities':probabilities,'maximum_workflow_decisions':200,'gate_escape_given_bad_proposal':.01,'detection_bound_seconds':d,'propagation_and_cache_bound_seconds':c,'one_sided_alpha':alpha},'results':result,'assumptions':['Workflow illustration assumes identical independent event probabilities across decisions; event semantics must be defined consistently. The gated example uses a conditional escape probability, not an independence assertion within one decision.','Revocation model is a worst-case bound from an assumed policy-invalidating event. Detection and propagation/cache delays must actually be bounded and checked at enforcement. Expiry-only validation does not inherit the online bound.','Zero-failure interval assumes independent representative Bernoulli trials with a constant unknown probability. Adaptive, duplicated or clustered cases do not automatically meet this condition.'],'exclusions':['No observed benchmark scores, attacks against real systems, exploit payloads, credentials, customer data or measured product-performance claims.','No model of correlated workflow errors, adaptive adversary probability, clock uncertainty, unconstrained refresh credentials or actual implementation failure frequency.'],'software':{'numpy':np.__version__,'matplotlib':matplotlib.__version__}}
(OUT/'model-parameters.json').write_text(json.dumps(manifest,indent=2)+'\n');print(json.dumps(result,indent=2))
