okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3cabb9e3f
main
1"""Raster MCP delivery: cache bounds, authenticated downloads and vision forwarding; no GPU.""" 2import base64 3import json 4import tempfile 5import unittest 6import urllib .error 7import urllib .request 8from pathlib import Path 9from unittest .mock import patch 10from serve .mcp import cache_images ,hub_from_config 11from serve .frontend import ChatTemplate ,images_of 12from serve .server import ByteTokenizer ,Service ,serve 13from serve .test_mcp import ScriptedEngine ,call_script 14from serve import test_mcp as fixtures 15PNG = base64 .b64decode ('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jB0kAAAAASUVORK5CYII=' ) 16 17def image (data = PNG ,mime = 'image/png' ): 18return {'type' :'image' ,'mimeType' :mime ,'data' :base64 .b64encode (data ).decode ()} 19 20class Configuration (unittest .TestCase ): 21def test_documented_switch_reaches_hub_and_tool_result (self ): 22hub = hub_from_config ({'mcp_servers' : {'fake' : {'command' :'unused' }}, 23'mcp' : {'image_results' :True }}) 24self .assertTrue (hub .settings ['image_results' ]) 25server = hub .servers ['fake' ] 26server .status = 'ready' 27server .tools = [{'name' :'image' ,'inputSchema' : {}}] 28with tempfile .TemporaryDirectory ()as tmp : 29hub .media_dir = Path (tmp ) 30with patch .object (server ,'call' ,return_value = {'content' : [image ()]}): 31result = hub .call ('fake__image' , {}) 32self .assertEqual (len (result ['images' ]),1 ) 33self .assertEqual (result ['model_content' ][1 ]['type' ],'image' ) 34 35def test_disabled_and_omitted_switch_stay_off (self ): 36for settings in ({}, {'image_results' :False }): 37with self .subTest (settings = settings ): 38hub = hub_from_config ({'mcp_servers' : {'fake' : {'command' :'unused' }},'mcp' :settings }) 39self .assertFalse (hub .settings ['image_results' ]) 40 41def test_switch_rejects_non_booleans (self ): 42for value in ('true' ,'false' ,0 ,1 ,None , [], {}): 43with self .subTest (value = value ),self .assertRaisesRegex (SystemExit ,'expected a boolean' ): 44hub_from_config ({'mcp_servers' : {'fake' : {'command' :'unused' }}, 45'mcp' : {'image_results' :value }}) 46 47class Cache (unittest .TestCase ): 48 49def test_image_text_obeys_result_cap (self ): 50from serve .mcp import McpHub 51hub = McpHub ({'fake' : {'command' :'unused' }}, {'max_result_chars' :1000 ,'image_results' :True }) 52server = hub .servers ['fake' ] 53server .status = 'ready' 54server .tools = [{'name' :'image' ,'inputSchema' : {}}] 55with tempfile .TemporaryDirectory ()as tmp : 56hub .media_dir = Path (tmp ) 57with patch .object (server ,'call' ,return_value = {'content' : [{'type' :'text' ,'text' :'x' * 100000 },image ()]}): 58result = hub .call ('fake__image' , {}) 59self .assertTrue (result ['truncated' ]) 60self .assertLessEqual (len (result ['model_content' ][0 ]['text' ]),len (result ['text' ])) 61self .assertNotIn ('x' * 1001 ,result ['model_content' ][0 ]['text' ]) 62self .assertEqual (len (result ['images' ]),1 ) 63 64def test_disabled_is_identical_to_text_only_result (self ): 65from serve .mcp import McpHub ,result_text 66hub = McpHub ({'fake' : {'command' :'unused' }}) 67server = hub .servers ['fake' ] 68server .status = 'ready' 69server .tools = [{'name' :'image' ,'inputSchema' : {}}] 70result = {'content' : [{'type' :'text' ,'text' :'hello' },image ()]} 71with tempfile .TemporaryDirectory ()as tmp : 72hub .media_dir = Path (tmp )/ 'unused' 73with patch .object (server ,'call' ,return_value = result ),patch ('serve.mcp.cache_images' )as cache : 74output = hub .call ('fake__image' , {}) 75cache .assert_not_called () 76self .assertEqual (output ['text' ],result_text (result )) 77self .assertNotIn ('images' ,output ) 78self .assertNotIn ('model_content' ,output ) 79self .assertFalse (hub .media_dir .exists ()) 80 81def test_cache_failure_keeps_text_result (self ): 82from serve .mcp import McpHub 83hub = McpHub ({'fake' : {'command' :'unused' }}, {'image_results' :True }) 84server = hub .servers ['fake' ] 85server .status = 'ready' 86server .tools = [{'name' :'image' ,'inputSchema' : {}}] 87hub .media_dir = Path ('unused' ) 88with patch .object (server ,'call' ,return_value = {'content' : [{'type' :'text' ,'text' :'hello' },image ()]}),patch ('serve.mcp.cache_images' ,side_effect = OSError ('disk full' )): 89output = hub .call ('fake__image' , {}) 90self .assertTrue (output ['ok' ]) 91self .assertIn ('hello' ,output ['text' ]) 92self .assertNotIn ('model_content' ,output ) 93 94def test_null_and_non_object_content (self ): 95with tempfile .TemporaryDirectory ()as tmp : 96self .assertEqual (cache_images ({'content' :None },tmp ), []) 97self .assertEqual (cache_images ({'content' : [None ,False ,'bad' ,image ()]},tmp ),cache_images ({'content' : [image ()]},tmp )) 98 99def test_cache_deduplicates_and_preserves_bytes (self ): 100with tempfile .TemporaryDirectory ()as tmp : 101a = cache_images ({'content' : [image ()]},tmp ) 102b = cache_images ({'content' : [image ()]},tmp ) 103self .assertEqual (a ,b ) 104self .assertEqual (len (list (Path (tmp ).iterdir ())),1 ) 105self .assertEqual ((Path (tmp )/ a [0 ]['url' ].split ('/' )[- 1 ]).read_bytes (),PNG ) 106 107def test_rejects_invalid_and_active_content (self ): 108with tempfile .TemporaryDirectory ()as tmp : 109blocks = [image (b'not a PNG' ),image (b'<svg/>' ,'image/svg+xml' ), {'type' :'image' ,'mimeType' :'image/png' ,'data' :'***' }] 110self .assertEqual (cache_images ({'content' :blocks },tmp ), []) 111 112def test_caps_images_per_result (self ): 113with tempfile .TemporaryDirectory ()as tmp : 114self .assertEqual (len (cache_images ({'content' : [image ()]* 8 },tmp )),4 ) 115 116def test_authenticated_download_and_traversal (self ): 117with tempfile .TemporaryDirectory ()as tmp : 118media = cache_images ({'content' : [image ()]},tmp )[0 ] 119tok = ByteTokenizer () 120svc = Service (ScriptedEngine (tok , ['OK' ]),tok ,ChatTemplate (Path (__file__ ).parent / 'chat_template.jinja' )) 121 122class Hub : 123media_dir = tmp 124svc .mcp = Hub () 125svc .api_key = 'test-key' 126httpd = serve (svc ,port = 0 ) 127base = f'http://127.0.0.1: { httpd . server_address [ 1 ] } /' 128try : 129with self .assertRaises (urllib .error .HTTPError )as error : 130urllib .request .urlopen (base + media ['url' ]) 131self .assertEqual (error .exception .code ,401 ) 132req = urllib .request .Request (base + media ['url' ],headers = {'Authorization' :'Bearer test-key' }) 133with urllib .request .urlopen (req )as response : 134self .assertEqual (response .read (),PNG ) 135self .assertEqual (response .headers ['Content-Type' ],'image/png' ) 136req = urllib .request .Request (base + 'tool-media/../../secret.png' ,headers = {'Authorization' :'Bearer test-key' }) 137with self .assertRaises (urllib .error .HTTPError )as error : 138urllib .request .urlopen (req ) 139self .assertEqual (error .exception .code ,404 ) 140finally : 141httpd .shutdown () 142httpd .server_close () 143 144class HistoryReferences (unittest .TestCase ): 145 146def test_reference_resolves_only_to_cache (self ): 147with tempfile .TemporaryDirectory ()as tmp : 148im = cache_images ({'content' : [image ()]},tmp )[0 ] 149name = im ['url' ].split ('/' )[- 1 ] 150tok = ByteTokenizer () 151svc = Service (ScriptedEngine (tok , ['OK' ]),tok ,ChatTemplate (Path (__file__ ).parent / 'chat_template.jinja' )) 152 153class Hub : 154media_dir = tmp 155svc .mcp = Hub () 156message = [{'role' :'tool' ,'content' : [{'type' :'image' ,'source' :'strata-tool-media:' + name }]}] 157with patch .object (svc ,'_note_unreadable_tool_images' ,return_value = {}): 158with self .assertRaisesRegex (ValueError ,'without the vision encoder' ): 159svc .prepare (message , [], {},16 ) 160self .assertEqual (images_of (message ), [str (Path (tmp )/ name )]) 161 162def test_mixed_missing_and_valid_pictures_keeps_valid_vision (self ): 163with tempfile .TemporaryDirectory ()as tmp : 164media = cache_images ({'content' : [image ()]},tmp )[0 ] 165source = str (Path (tmp )/ media ['url' ].split ('/' )[- 1 ]) 166rows = Path (tmp )/ 'img.sve' 167rows .write_bytes (b'rows' ) 168class Vision : 169dir = Path (tmp ) 170 171def encode (self ,value ): 172if value != source : 173raise AssertionError ('Only the valid cached image may reach the encoder' ) 174return rows ,3 175tok = ByteTokenizer () 176svc = Service (ScriptedEngine (tok , ['OK' ]),tok , 177ChatTemplate (Path (__file__ ).parent / 'chat_template.jinja' ),vision = Vision ()) 178class Hub : 179media_dir = tmp 180svc .mcp = Hub () 181messages = [{'role' :'tool' ,'content' : [ 182 {'type' :'text' ,'text' :'Retain this text.' }, 183 {'type' :'image' ,'source' :'strata-tool-media:' + '0' * 64 + '.png' }, 184 {'type' :'image' ,'source' :'strata-tool-media:' + media ['url' ].split ('/' )[- 1 ]}]}] 185try : 186ids ,_ ,_ = svc .prepare (messages , [], {},16 ) 187prompt = tok .decode (ids ) 188self .assertIn ('Retain this text.' ,prompt ) 189self .assertIn ('[image omitted:' ,prompt ) 190self .assertEqual (images_of (messages ), [source ]) 191self .assertEqual (ids .count (tok .encode ('<|image_pad|>' ,parse_special = True )[0 ]),3 ) 192finally : 193if svc .embeddings .path : 194svc .embeddings .path .unlink (missing_ok = True ) 195 196def test_bad_reference_cannot_read_other_files (self ): 197tok = ByteTokenizer () 198svc = Service (ScriptedEngine (tok , ['OK' ]),tok ,ChatTemplate (Path (__file__ ).parent / 'chat_template.jinja' )) 199with self .assertRaisesRegex (ValueError ,'invalid tool image reference' ): 200svc .prepare ([{'role' :'tool' ,'content' : [{'type' :'image' ,'source' :'strata-tool-media:../../secret.png' }]}], [], {},16 ) 201 202class ImageLoop (unittest .TestCase ): 203setUp = fixtures .ToolLoop .setUp 204tearDown = fixtures .ToolLoop .tearDown 205start = fixtures .ToolLoop .start 206post = fixtures .ToolLoop .post 207chunks = staticmethod (fixtures .ToolLoop .chunks ) 208 209def check_stale_history (self ,state ): 210self .start ('</think>\n\nText reply survives.' ) 211with tempfile .TemporaryDirectory ()as tmp : 212self .hub .media_dir = Path (tmp )if state == 'missing' else None 213if state == 'no_hub' : 214self .svc .mcp = None 215history = [ 216 {'role' :'user' ,'content' :'Create a picture' }, 217 {'role' :'assistant' ,'content' :'' ,'tool_calls' : [ 218 {'id' :'old' ,'type' :'function' ,'function' : {'name' :'fake__echo' ,'arguments' :'{}' }}]}, 219 {'role' :'tool' ,'tool_call_id' :'old' ,'content' : [ 220 {'type' :'text' ,'text' :'Keep this original tool text.' }, 221 {'type' :'image_url' ,'image_url' : {'url' :'strata-tool-media:' + '0' * 64 + '.png' }}]}, 222 {'role' :'user' ,'content' :'Continue with text only' }] 223# API clients resend the original unmodified history on every later turn. 224for turn in range (2 ): 225for stream in (False ,True ): 226with self .subTest (state = state ,turn = turn ,stream = stream ): 227code ,text = self .post ({'messages' :history },stream = stream ) 228self .assertEqual (code ,200 ,text ) 229if stream : 230answer = '' .join (c ['choices' ][0 ]['delta' ].get ('content' ,'' )for c in self .chunks (text )) 231else : 232answer = json .loads (text )['choices' ][0 ]['message' ]['content' ] 233self .assertIn ('Text reply survives.' ,answer ) 234prompt = self .engine .prompt_text (turn * 2 + int (stream )) 235self .assertIn ('Keep this original tool text.' ,prompt ) 236self .assertIn ('[image omitted:' ,prompt ) 237self .assertNotIn ('strata-tool-media:' ,prompt ) 238 239def test_missing_cache_history_continues_across_turns (self ): 240self .check_stale_history ('missing' ) 241 242def test_disabled_cache_history_continues_across_turns (self ): 243self .check_stale_history ('disabled' ) 244 245def test_removed_mcp_history_continues_across_turns (self ): 246self .check_stale_history ('no_hub' ) 247 248def test_malformed_history_still_rejected_over_http (self ): 249self .start ('</think>\n\nShould not run.' ) 250self .svc .mcp = None 251for name in ('../../secret.png' ,'a' * 64 + '.svg' ,'A' * 64 + '.png' ,'short.png' ): 252with self .subTest (name = name ): 253code ,text = self .post ({'messages' : [{'role' :'tool' ,'content' : [ 254 {'type' :'image_url' ,'image_url' : {'url' :'strata-tool-media:' + name }}]}]},stream = False ) 255self .assertEqual (code ,400 ) 256self .assertIn ('invalid tool image reference' ,text ) 257self .assertEqual (self .engine .prompts , []) 258 259def test_default_stream_has_no_image_fields (self ): 260self .start (call_script ('fake__echo' ,text = 'hello' ),'</think>\n\nDone.' ) 261code ,text = self .post ({'strata_mcp' :True }) 262self .assertEqual (code ,200 ) 263event = [c ['strata_mcp' ]for c in self .chunks (text )if c .get ('strata_mcp' , {}).get ('event' )== 'result' ][0 ] 264self .assertEqual (set (event ), {'event' ,'id' ,'ok' ,'text' ,'chars' ,'truncated' ,'ms' }) 265 266def test_image_result_streams_and_reaches_vision_prepare (self ): 267with tempfile .TemporaryDirectory ()as tmp : 268self .hub .settings ['image_results' ]= True 269self .hub .media_dir = Path (tmp ) 270im = cache_images ({'content' : [image ()]},tmp ) 271source = str (Path (tmp )/ im [0 ]['url' ].split ('/' )[- 1 ]) 272self .start (call_script ('fake__echo' ,text = 'picture' ),'</think>\n\nImage received.' ) 273self .svc .vision = object () 274native = self .svc .prepare 275seen = [] 276 277def prepare (messages ,* args ,** kwargs ): 278seen .extend (images_of (messages )) 279clean = [{** m ,'content' :'image delivered' }if isinstance (m .get ('content' ),list )else m for m in messages ] 280return native (clean ,* args ,** kwargs ) 281result = {'ok' :True ,'text' :'image delivered' ,'chars' :15 ,'truncated' :False ,'ms' :1 ,'images' :im ,'model_content' : [{'type' :'text' ,'text' :'image delivered' }, {'type' :'image' ,'source' :source }]} 282with patch .object (self .hub ,'call' ,return_value = result ),patch .object (self .svc ,'prepare' ,side_effect = prepare ): 283code ,text = self .post ({'strata_mcp' :True }) 284self .assertEqual (code ,200 ) 285self .assertIn (source ,seen ) 286events = [c ['strata_mcp' ]for c in self .chunks (text )if 'strata_mcp' in c ] 287self .assertEqual (events [- 1 ]['images' ],im ) 288answer = '' .join ((c ['choices' ][0 ]['delta' ].get ('content' ,'' )for c in self .chunks (text ))) 289self .assertIn ('Image received.' ,answer )