Repository navigation
Expand file tree
/
Copy pathaddon.py
More file actions
6441 lines (5533 loc) · 265 KB
/
Copy pathaddon.py
File metadata and controls
6441 lines (5533 loc) · 265 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Code created by Siddharth Ahuja: www.github.com/ahujasid © 2025
import re
import textwrap
import bpy
import mathutils
import json
import threading
import socket
import queue
import time
import requests
import tempfile
import traceback
import os
import shutil
import uuid
import zipfile
import zlib
from bpy.props import IntProperty, BoolProperty
import io
from datetime import datetime
import hashlib, hmac, base64
import os.path as osp
from collections import deque
from urllib.parse import quote, urlencode, urlparse, urlunparse, parse_qsl
from contextlib import contextmanager, redirect_stdout, suppress
from bpy.app.handlers import persistent
bl_info = {
"name": "MCP for Blender",
"author": "Siddharth Ahuja",
"version": (1, 8),
"blender": (3, 0, 0),
"location": "View3D > Sidebar > MCP for Blender",
"description": "Connect Blender to Claude via MCP",
"doc_url": "https://mcp-for-blender.com/",
"category": "Interface",
}
# Keep in sync with blender_mcp.addon_manager.EXPECTED_ADDON_PROTOCOL_VERSION.
ADDON_PROTOCOL_VERSION = 13
# Per-snapshot object cap for get_world_state_snapshot. Keep in sync with
# blender_mcp.trajectory.MAX_SNAPSHOT_OBJECTS.
MAX_SNAPSHOT_OBJECTS = 4000
# Selected-name cap for get_world_state_snapshot: select-all in a large scene
# would otherwise make `selected` the dominant field of both step snapshots.
# Keep in sync with blender_mcp.trajectory.MAX_SNAPSHOT_SELECTED.
MAX_SNAPSHOT_SELECTED = 1000
RODIN_FREE_TRIAL_KEY = "vibecoding"
DISCORD_URL = "https://discord.gg/SNqPn4TcKQ"
# Add User-Agent as required by Poly Haven API
REQ_HEADERS = requests.utils.default_headers()
REQ_HEADERS.update({"User-Agent": "blender-mcp"})
# Set when the user disconnects so opening another blend file does not restart
# the server behind their back. A manual connect or add-on reload clears it.
_user_stopped_server = False
def _blendermcp_port_has_listener(host, port):
"""Return True when another process already owns the MCP endpoint."""
probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
probe.settimeout(0.15)
try:
return probe.connect_ex((host, port)) == 0
finally:
probe.close()
def _blendermcp_ensure_server_running():
"""Start the bridge after Blender's UI and scene context are ready.
Returning a delay asks Blender's timer system to retry when a launch-time
socket or context race prevented the first attempt.
"""
if bpy.app.background:
return None
scene = getattr(bpy.context, "scene", None)
if scene is None:
return 0.5
server = getattr(bpy.types, "blendermcp_server", None)
if not scene.blendermcp_auto_start_server or _user_stopped_server:
scene.blendermcp_server_running = bool(server is not None and server.running)
return None
port = scene.blendermcp_port
if server is None:
if _blendermcp_port_has_listener("localhost", port):
scene.blendermcp_server_running = False
print(f"BlenderMCP: port {port} is already in use; auto-start skipped.")
return None
server = BlenderMCPServer(port=port)
bpy.types.blendermcp_server = server
if not server.running:
# Safe while stopped and necessary when a newly loaded scene selects a
# different port. Never retarget an active connection.
server.port = port
server.start()
scene.blendermcp_server_running = server.running
return None if server.running else 1.0
def _blendermcp_schedule_auto_start(delay=0.5):
"""Schedule one persistent startup callback if none is already pending."""
if not bpy.app.timers.is_registered(_blendermcp_ensure_server_running):
bpy.app.timers.register(
_blendermcp_ensure_server_running,
first_interval=delay,
persistent=True,
)
@persistent
def _blendermcp_load_post(_unused):
"""Retry auto-start after Blender loads a startup file or another blend."""
_blendermcp_schedule_auto_start()
def _blendermcp_register_auto_start():
"""Install the load handler and defer the initial startup attempt."""
global _user_stopped_server
_user_stopped_server = False
if _blendermcp_load_post not in bpy.app.handlers.load_post:
bpy.app.handlers.load_post.append(_blendermcp_load_post)
_blendermcp_schedule_auto_start()
def _blendermcp_unregister_auto_start():
"""Remove callbacks owned by the add-on before it is disabled."""
if _blendermcp_load_post in bpy.app.handlers.load_post:
bpy.app.handlers.load_post.remove(_blendermcp_load_post)
if bpy.app.timers.is_registered(_blendermcp_ensure_server_running):
bpy.app.timers.unregister(_blendermcp_ensure_server_running)
#region Poly Pizza constants and helpers
POLYPIZZA_API_BASE = "https://api.poly.pizza/v1.1"
# The MCP server resolves human-friendly category/licence names to the numeric
# ids the API filters on, so only ids arrive here. Every query parameter of
# the API is Capitalized (Limit, Page, Category, License, Animated — see
# poly.pizza/apispec/v1.1.yaml): lowercase variants are accepted with HTTP 200
# and then silently ignored, so the capitalisation is load-bearing.
def _polypizza_category_id(category):
"""Validate a numeric category id (names are resolved by the MCP server)."""
if category is None or category == "":
return None
if isinstance(category, bool) or not (
isinstance(category, int)
or (isinstance(category, str) and category.strip().lstrip("-").isdigit())
):
raise ValueError(f"Poly Pizza category must be a numeric id in 0-11, got {category!r}")
value = int(category)
if not 0 <= value <= 11:
raise ValueError(f"Poly Pizza category id {value} is out of range (valid ids are 0-11)")
return value
def _polypizza_licence_id(licence):
"""Validate a numeric licence id (names are resolved by the MCP server)."""
if licence is None or licence == "":
return None
if isinstance(licence, bool) or not (
isinstance(licence, int)
or (isinstance(licence, str) and licence.strip().lstrip("-").isdigit())
):
raise ValueError(f"Poly Pizza licence must be 0 (CC-BY) or 1 (CC0), got {licence!r}")
value = int(licence)
if value not in (0, 1):
raise ValueError(f"Poly Pizza licence id {value} is invalid (0 = CC-BY, 1 = CC0)")
return value
def _polypizza_filter_params(category=None, licence=None, animated=False):
"""Build the query filters for a Poly Pizza search.
Keys are Capitalized and values numeric because the API silently ignores
anything else. `Animated` is omitted unless animated-only results were asked
for: the server treats `Animated=0` as falsy and does not filter on it.
"""
params = {}
category_id = _polypizza_category_id(category)
if category_id is not None:
params["Category"] = category_id
licence_id = _polypizza_licence_id(licence)
if licence_id is not None:
params["License"] = licence_id
if animated:
params["Animated"] = 1
return params
def _polypizza_summarize_model(model):
"""Trim an API record down to the fields worth sending back over MCP."""
creator = model.get("Creator") or {}
return {
"ID": model.get("ID"),
"Title": model.get("Title"),
"Creator": creator.get("Username") if isinstance(creator, dict) else None,
"Licence": model.get("Licence"),
"Tri Count": model.get("Tri Count"),
"Animated": bool(model.get("Animated")),
"Category": model.get("Category"),
"Tags": model.get("Tags") or [],
"Thumbnail": model.get("Thumbnail"),
}
def _polypizza_cdn_error(status_code, headers, content):
"""Describe a CDN response that is not a GLB, or None when it is one.
static.poly.pizza sits behind Cloudflare bot management and answers 403 with
an HTML challenge from datacenter IPs. That is neither an auth failure nor a
missing model, so it gets its own message.
"""
if status_code == 200 and content[:4] == b"glTF":
return None
headers = headers or {}
content_type = ""
for key in ("Content-Type", "content-type"):
value = headers.get(key)
if value:
content_type = str(value).lower()
break
challenged = bool(headers.get("cf-mitigated") or headers.get("Cf-Mitigated"))
looks_like_html = "text/html" in content_type or content[:1] == b"<"
if challenged or (looks_like_html and status_code != 200):
return (
f"Poly Pizza's CDN returned a Cloudflare bot-protection challenge (HTTP {status_code}) "
"instead of the model file. This is not an API key problem - static.poly.pizza takes no "
"API key - and the model exists. The CDN blocks datacenter, VPN and cloud IPs; retry from "
"a residential connection, or download the .glb by hand from https://poly.pizza and import "
"it with File > Import > glTF 2.0."
)
if status_code != 200:
return f"Poly Pizza model file download failed with status code {status_code}"
if looks_like_html:
return (
"Poly Pizza's CDN returned an HTML page instead of a GLB file. The download link may have "
"expired; search again to get a fresh one."
)
return "Poly Pizza returned a file that is not a valid GLB (missing glTF magic bytes)"
#endregion
#region Poly Haven constants and helpers
POLYHAVEN_API_BASE = "https://api.polyhaven.com"
# Versioned, so Poly Haven can tell which integration its traffic is coming from
# and how many people it is serving. Kept separate from the shared REQ_HEADERS
# because Poly Pizza sends that one too.
POLYHAVEN_HEADERS = dict(REQ_HEADERS)
POLYHAVEN_HEADERS["User-Agent"] = (
"blender-mcp/" + ".".join(str(part) for part in bl_info["version"])
+ " (+https://github.com/ahujasid/blender-mcp)"
)
# (connect, read). The read timeout applies per socket read rather than to the
# whole transfer, so streaming a large HDRI never trips it - but a dead
# connection no longer hangs Blender's main thread indefinitely.
POLYHAVEN_API_TIMEOUT = (10, 30)
POLYHAVEN_FILE_TIMEOUT = (10, 60)
POLYHAVEN_CHUNK_SIZE = 1024 * 1024
# What we can actually import, per asset type. Checked BEFORE downloading
# anything: the API lists a `usd` entry for every model, which used to pass the
# "is this format present?" guard, get downloaded in full, and only then be
# rejected as an unsupported format.
POLYHAVEN_SUPPORTED_FORMATS = {
"hdris": ("hdr", "exr"),
"textures": ("jpg", "png", "exr"),
"models": ("blend",),
}
POLYHAVEN_DEFAULT_FORMATS = {"hdris": "hdr", "textures": "jpg", "models": "blend"}
# Models are imported from the .blend and nothing else. Poly Haven authors its
# models in Blender and generates every other format from that file, so glTF and
# FBX are lossy renderings of a material that is sitting right there - node
# groups collapse to a base colour, and procedural setups do not survive at all.
#
# glTF stays as a fallback for one case only: a .blend written by a newer
# Blender than the one running, which cannot be opened at all. See
# _polyhaven_blend_version.
POLYHAVEN_MODEL_FALLBACK_FORMAT = "gltf"
# Poly Haven's /files map keys, and what each map drives. Their casing is
# inconsistent and load-bearing - "Diffuse", "Rough", "Metal" and
# "Displacement" are capitalised while "nor_gl" and "arm" are not - so these
# are matched exactly instead of being lower-cased and guessed at.
#
# This is the set that drives a Principled BSDF directly, and it covers what
# Poly Haven's own .blend materials use for the large majority of the library.
# Of the rest the API offers, "arm" is an ORM repacking of maps already here,
# "rough_ao" is roughness with AO baked in, and "nor_dx" is the other normal map
# convention. "AO", "spec" and "Bump" need extra nodes to be worth anything.
#
# It is not a complete match for every asset: measured across the 860 published
# textures, 114 ship a .blend referencing a map not in this table - 74 use "AO",
# and 30 fabrics drive Anisotropic, Anisotropic Rotation and IOR from
# "anisotropy_strength", "anisotropy_rotation" and "spec_ior". Those materials
# come out flatter here than the artist built them.
#
# Downloading every map and then leaving most of them unconnected is what cost
# 7.4MB to build a 1k material that connected 1.9MB of it. This table brings
# that asset down to 3.9MB, all of it wired.
POLYHAVEN_TEXTURE_MAPS = {
"Diffuse": "base_color",
"Rough": "roughness",
"Metal": "metallic",
"Displacement": "displacement",
"nor_gl": "normal",
"nor_dx": "normal",
}
# Only the albedo is colour data; every other map is values the shader reads.
POLYHAVEN_COLOR_ROLES = {"base_color"}
POLYHAVEN_SLUG_RE = re.compile(r"^[A-Za-z0-9_-]{1,80}$")
POLYHAVEN_SITE = "https://polyhaven.com"
# `type` is an integer in the API's asset records.
POLYHAVEN_ASSET_TYPES = {0: "hdris", 1: "textures", 2: "models"}
POLYHAVEN_SEARCH_LIMIT = 20
POLYHAVEN_SEARCH_MAX_LIMIT = 50
# Levels of the category tree returned when every asset type is asked for at
# once. Filtering on a category is inclusive, so a parent still selects
# everything nested beneath it.
POLYHAVEN_TAXONOMY_DEPTH_ALL = 2
# Poly Haven publishes thumbnails at 256px. The CDN resizes from the query
# string, so a preview worth looking at costs no stored file.
POLYHAVEN_PREVIEW_SIZE = 512
class PolyHavenAPIError(Exception):
"""A non-2xx from the Poly Haven API, with the status kept.
Needed because 429 and 503 want different handling from a generic failure:
one means back off, the other means the search index is unavailable and the
API is telling us to fall back to matching keywords ourselves.
"""
def __init__(self, status, retry_after=None):
super().__init__(f"HTTP {status}")
self.status = status
self.retry_after = retry_after
# Poly Haven serves the asset list with `Cache-Control: max-age=43200` and an
# ETag, and both were being discarded: every search re-fetched all 2.44MB of it.
# The TTL here matches theirs, and once it lapses the ETag usually turns the
# refetch into a 304.
POLYHAVEN_CACHE_TTL = 12 * 60 * 60
# Bounded so a session that searches every type and taxonomy cannot grow without
# limit. The asset list is by far the largest entry, and there are four of those.
POLYHAVEN_CACHE_MAX_ENTRIES = 16
_polyhaven_cache = {}
# A counter rather than a clock. time.time() has ~15ms resolution on Windows, so
# entries touched inside one burst of calls tie, and min() then evicts whichever
# happens to come first in the dict - which can be the very entry this is
# protecting.
_polyhaven_cache_clock = 0
def _polyhaven_cache_touch():
global _polyhaven_cache_clock
_polyhaven_cache_clock += 1
return _polyhaven_cache_clock
def _polyhaven_cache_key(path, params):
return path, tuple(sorted((params or {}).items()))
def _polyhaven_api_get(path, params=None, cache=False):
"""GET a Poly Haven API endpoint, raising on anything but a 2xx.
With cache=True the response is held for POLYHAVEN_CACHE_TTL, and revalidated
with If-None-Match after that rather than re-downloaded.
"""
key = _polyhaven_cache_key(path, params)
entry = _polyhaven_cache.get(key) if cache else None
headers = dict(POLYHAVEN_HEADERS)
if entry is not None:
if time.time() - entry["fetched"] < POLYHAVEN_CACHE_TTL:
entry["used"] = _polyhaven_cache_touch()
return entry["payload"]
if entry.get("etag"):
headers["If-None-Match"] = entry["etag"]
response = requests.get(
f"{POLYHAVEN_API_BASE}/{path}",
params=params,
headers=headers,
timeout=POLYHAVEN_API_TIMEOUT,
)
if entry is not None and response.status_code == 304:
entry["fetched"] = time.time()
entry["used"] = _polyhaven_cache_touch()
return entry["payload"]
if response.status_code >= 400:
raise PolyHavenAPIError(
response.status_code,
getattr(response, "headers", {}).get("Retry-After"),
)
payload = response.json()
if cache:
if len(_polyhaven_cache) >= POLYHAVEN_CACHE_MAX_ENTRIES:
# Least recently USED, not least recently fetched. Evicting on fetch
# time is strictly FIFO, because a hit never refreshes it - and the
# asset list is by construction the first thing fetched in a session
# and then only ever read, so it was always the first entry thrown
# out, displaced by one-shot search payloads a tenth of a percent its
# size. Its ETag went with it, so the refetch could not revalidate.
coldest = min(_polyhaven_cache, key=lambda k: _polyhaven_cache[k]["used"])
_polyhaven_cache.pop(coldest, None)
_polyhaven_cache[key] = {
"payload": payload,
"etag": getattr(response, "headers", {}).get("ETag"),
"fetched": time.time(),
"used": _polyhaven_cache_touch(),
}
return payload
def _polyhaven_valid_slug(asset_id):
"""Poly Haven slugs are always [A-Za-z0-9_-].
Asset ids arrive from the model and are used to build the names of the files
downloaded into the temporary directory, so they are checked once here
rather than escaped differently in each place.
"""
return bool(POLYHAVEN_SLUG_RE.match(asset_id or ""))
def _polyhaven_download(file_info, dest_path):
"""Stream one file to dest_path, verifying the md5 the API published.
Streaming matters: resolution="24k", file_format="exr" is a valid call and
that file is 2.4GB, which the previous response.content read materialised
in memory in full before writing it back out again.
"""
expected = file_info.get("md5")
response = requests.get(
file_info["url"],
headers=POLYHAVEN_HEADERS,
stream=True,
timeout=POLYHAVEN_FILE_TIMEOUT,
)
response.raise_for_status()
digest = hashlib.md5()
with open(dest_path, "wb") as f:
for chunk in response.iter_content(chunk_size=POLYHAVEN_CHUNK_SIZE):
if not chunk:
continue
digest.update(chunk)
f.write(chunk)
if expected and digest.hexdigest() != expected:
with suppress(OSError):
os.unlink(dest_path)
raise ValueError(
f"Checksum mismatch for {os.path.basename(dest_path)}: "
"the download was truncated or corrupted"
)
return dest_path
def _polyhaven_uncompress_head(raw):
"""The start of a .blend, which is usually compressed on disk.
Blender wrote gzip up to 2.93 and zstd from 3.0. Both decompressors are
incremental, so a truncated prefix decompresses to a shorter prefix rather
than raising.
"""
if raw[:7] == b"BLENDER":
return raw
if raw[:2] == b"\x1f\x8b":
with suppress(Exception):
return zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(raw)
return None
try:
import zstandard
except ImportError:
# Not bundled with every Blender build. Without it the version cannot be
# read, and the import falls back to trying the append and handling the
# failure - which is the same outcome, one download later.
return None
with suppress(Exception):
return zstandard.ZstdDecompressor().decompressobj().decompress(raw)
return None
def _polyhaven_blend_version(path):
"""(major, minor) of the Blender that wrote this .blend, or None.
Blender cannot open a file written by a newer version than itself, and Poly
Haven's models span 2.93 to 5.0 because each was saved by whichever Blender
compiled it. The version is in the file header, in one of two layouts:
up to Blender 4.4: BLENDER-v293
from Blender 4.5: BLENDER17-01v0502
where the digits straight after BLENDER are the header's own length, and the
version field grows from three characters to four.
"""
try:
with open(path, "rb") as f:
head = _polyhaven_uncompress_head(f.read(1 << 16))
except OSError:
return None
if not head or not head.startswith(b"BLENDER"):
return None
try:
if head[7:9].isdigit():
return int(head[13:15]), int(head[15:17])
return int(head[9:10]), int(head[10:12])
except (ValueError, IndexError):
return None
def _polyhaven_category_paths(nodes, depth=None, _level=1):
"""Flatten the category tree to its paths, which is what filters take."""
paths = []
for node in nodes or []:
if node.get("path"):
paths.append(node["path"])
if depth is None or _level < depth:
paths.extend(_polyhaven_category_paths(node.get("children"), depth, _level + 1))
return paths
def _polyhaven_taxonomy(asset_type, depth=None):
"""The category tree and attribute schema for one asset type, trimmed.
The raw response is 60-80KB per type, most of it descriptions, UUIDs and
URL slugs that nothing here uses. The paths are what a `categories` filter
takes, and matching on them is inclusive, so a parent path selects
everything beneath it.
"""
payload = _polyhaven_api_get(f"taxonomy/{quote(asset_type, safe='')}", cache=True)
attributes = {}
for key, spec in (payload.get("attributes") or {}).items():
if isinstance(spec, dict):
attributes[key] = {
field: spec[field]
for field in ("type", "enum", "description")
if field in spec
}
return {
"type": payload.get("type") or asset_type,
"categories": _polyhaven_category_paths(payload.get("categories"), depth),
"attributes": attributes,
}
def _polyhaven_asset_url(slug):
return f"{POLYHAVEN_SITE}/a/{quote(slug, safe='')}"
def _polyhaven_asset_record(slug):
"""One asset's metadata, taken from the cached asset list where possible.
/info/{id} is the same record plus a few internal fields, so it is only
worth a request when the list has not already been fetched.
"""
for entry in _polyhaven_cache.values():
payload = entry.get("payload")
if isinstance(payload, dict):
record = payload.get(slug)
if isinstance(record, dict) and "name" in record:
return record
return _polyhaven_api_get(f"info/{quote(slug, safe='')}", cache=True)
def _polyhaven_preview_url(thumbnail_url, size=POLYHAVEN_PREVIEW_SIZE):
"""Resize the published thumbnail without losing its cache-busting `v`.
Poly Haven's CDN resizes from the query string, so a larger preview costs no
stored file - but `thumbnail_url` also carries a `v` holding a hash of the
asset's images, and a URL rebuilt by hand without it can be served a
year-old thumbnail for an asset whose renders have since been replaced.
"""
parts = urlparse(thumbnail_url)
params = dict(parse_qsl(parts.query, keep_blank_values=True))
if "width" in params or "height" in params:
params["width"] = str(size)
params["height"] = str(size)
return urlunparse(parts._replace(query=urlencode(params)))
def _polyhaven_summarize_asset(slug, record):
"""Trim an /assets record down to what is worth sending back over MCP.
The full record is around a kilobyte of JSON per asset and the whole page of
results crosses the socket in one message, so twenty untrimmed records is
most of what the model then has to read.
"""
authors = record.get("authors") or {}
summary = {
"id": slug,
"name": record.get("name") or slug,
"type": POLYHAVEN_ASSET_TYPES.get(record.get("type"), "unknown"),
"url": _polyhaven_asset_url(slug),
"authors": sorted(authors) if isinstance(authors, dict) else authors,
"downloads": record.get("download_count"),
}
for key in ("description", "category", "tags", "attributes", "max_resolution", "thumbnail_url"):
value = record.get(key)
if value:
summary[key] = value
# Real-world size in millimetres, published for every texture. Without it
# there is no way to know that a wall texture is 1.8m across, and the
# material gets whatever tiling the object's UVs happen to give it.
if record.get("dimensions"):
summary["dimensions_mm"] = record["dimensions"]
return summary
def _polyhaven_search(query, asset_type):
"""The full ranked list of slugs from Poly Haven's search endpoint.
The array order IS the ranking - it fuses a vector lane and a keyword lane
by position - so it must not be re-sorted by `score`, which reports vector
similarity alone.
No `limit` is sent. The endpoint returns the whole ranked list by design,
because callers are expected to intersect it with whatever they already
hold; asking for the first N and then filtering those would drop matches
that were simply further down.
"""
params = {"q": query}
if asset_type and asset_type != "all":
params["t"] = asset_type
payload = _polyhaven_api_get("search", params=params, cache=True)
return [r["slug"] for r in (payload.get("results") or []) if r.get("slug")]
def _polyhaven_keyword_match(query, assets):
"""The fallback the API asks for when it answers a search with 503."""
terms = [term for term in query.split() if term]
scored = []
for slug, record in assets.items():
haystack = " ".join([
slug.replace("_", " "),
str(record.get("name") or ""),
" ".join(record.get("tags") or []),
str(record.get("category") or ""),
]).lower()
hits = sum(1 for term in terms if term in haystack)
if hits:
scored.append((hits, record.get("download_count", 0), slug))
scored.sort(reverse=True)
return [slug for _hits, _downloads, slug in scored]
def _polyhaven_resolution_rank(resolution):
""""4k" -> 4, so resolutions sort numerically rather than as strings."""
try:
return int(str(resolution).rstrip("k"))
except (TypeError, ValueError):
return -1
def _polyhaven_sorted_resolutions(resolutions):
return sorted(resolutions, key=lambda res: (_polyhaven_resolution_rank(res) < 0,
_polyhaven_resolution_rank(res)))
def _polyhaven_available(files_data, asset_type):
"""Describe what an asset actually offers, for use in error messages.
The three "not available" errors this replaces were f-strings with nothing
interpolated into them, so an agent that guessed a resolution wrong had no
way to correct itself except to guess again - and each guess cost another
round trip.
"""
supported = POLYHAVEN_SUPPORTED_FORMATS.get(asset_type, ())
resolutions, formats = set(), set()
for by_resolution in files_data.values():
if not isinstance(by_resolution, dict):
continue
for resolution, by_format in by_resolution.items():
if not isinstance(by_format, dict):
continue
present = {fmt for fmt in by_format if fmt in supported}
if present:
resolutions.add(resolution)
formats |= present
return (
"available resolutions: "
+ (", ".join(_polyhaven_sorted_resolutions(resolutions)) or "none")
+ "; formats: "
+ (", ".join(sorted(formats)) or "none")
)
def _polyhaven_select_texture_maps(files_data, resolution, file_format):
"""The map keys worth downloading, in the order they should be laid out."""
selected = {}
for key, role in POLYHAVEN_TEXTURE_MAPS.items():
by_resolution = files_data.get(key)
if not isinstance(by_resolution, dict):
continue
if file_format in by_resolution.get(resolution, {}):
selected[key] = role
# OpenGL-convention normals are what Blender's Normal Map node expects.
# nor_dx is the same map with the green channel flipped, and is only worth
# fetching for the few assets that ship no nor_gl.
if "nor_gl" in selected:
selected.pop("nor_dx", None)
# A handful of textures name their albedo something other than "Diffuse" -
# the multi-variant fabrics ship col_1/col_2/col_03 instead of one map.
# Taking the first is a guess, but a material with no base colour at all is
# the failure this whole table exists to prevent.
if "base_color" not in selected.values():
for key in sorted(files_data):
if not key.lower().startswith(("col", "diff")):
continue
by_resolution = files_data.get(key)
if isinstance(by_resolution, dict) and file_format in by_resolution.get(resolution, {}):
selected[key] = "base_color"
break
return selected
def _polyhaven_set_colorspace(image, is_color_data):
"""Set a colorspace that exists on this Blender build.
The names moved around in 4.0, so each candidate is tried in turn rather
than assuming any one of them is present.
"""
candidates = ("sRGB",) if is_color_data else ("Non-Color", "Linear Rec.709", "Linear")
for name in candidates:
try:
image.colorspace_settings.name = name
return name
except Exception:
continue
return image.colorspace_settings.name
def _polyhaven_authors(asset_id):
"""Author names for an asset. Best effort - never fails an import."""
with suppress(Exception):
record = _polyhaven_asset_record(asset_id)
authors = record.get("authors") or {}
return sorted(authors) if isinstance(authors, dict) else list(authors)
return []
def _polyhaven_dimensions_mm(asset_id):
"""A texture's real-world size in millimetres. Best effort, like the authors.
Read from the record _polyhaven_authors has already fetched, so it costs no
extra request. Length two means a texture: a model's `dimensions` is a
bounding box, which is a different measurement and is readable from the
object itself once it is in the scene.
"""
with suppress(Exception):
dimensions = _polyhaven_asset_record(asset_id).get("dimensions")
if isinstance(dimensions, (list, tuple)) and len(dimensions) == 2:
return [float(value) for value in dimensions]
return None
def _polyhaven_mapping_node(node_tree):
"""The node every image node's Vector input is routed through, if it is still there."""
with suppress(Exception):
for node in node_tree.nodes:
if node.type == 'MAPPING':
return node
return None
def _polyhaven_tag(datablocks, asset_id, resolution=None, authors=None, dimensions=None):
"""Record where a datablock came from, in the file that keeps it.
Two jobs. It is the lookup key between downloading a texture and applying
it - the old code recovered the map type by parsing the image's name, taking
the last underscore-separated token, which turned "nor_gl" into "gl" and
left the download path and set_texture disagreeing about what a map was
called.
It is also where the asset came from, in the same shape the Poly Pizza
integration writes its polypizza_* properties. Poly Haven's assets are CC0
and require no attribution, ever - but custom properties are saved into the
.blend, so whoever opens the file in a year can still find the asset's page,
who made it, and the resolutions they did not download.
"""
for block in datablocks:
if block is None:
continue
with suppress(Exception):
block["polyhaven_id"] = asset_id
block["polyhaven_url"] = _polyhaven_asset_url(asset_id)
block["polyhaven_licence"] = "CC0"
if resolution:
block["polyhaven_resolution"] = resolution
if authors:
block["polyhaven_authors"] = ", ".join(authors)
elif "polyhaven_authors" in block.keys():
# The lookup is best-effort and comes back empty on any API
# failure. Every other field is overwritten regardless, so
# leaving a previous asset's artist behind on a datablock that
# is being re-tagged would credit them for somebody else's work.
del block["polyhaven_authors"]
# The texture's real-world size, the same measurement Poly Haven's
# own add-on writes onto the materials it ships. Saved into the
# .blend because tiling cannot be worked out without it and it is
# otherwise visible exactly once, in a search result.
if dimensions:
block["polyhaven_scale_mm"] = list(dimensions)
elif "polyhaven_scale_mm" in block.keys():
del block["polyhaven_scale_mm"]
#endregion
#region Manual edit capture
# Records what the human does in Blender while an MCP session is live.
MAX_EDIT_EVENTS = 256
# Operators that fire constantly during interactive work and carry no meaningful
# intent on their own.
_IGNORED_OPERATORS = frozenset({
"view3d.rotate",
"view3d.move",
"view3d.zoom",
"view3d.dolly",
"view3d.view_axis",
"view3d.view_orbit",
"view3d.view_pan",
"view3d.smoothview",
"view3d.cursor3d",
"wm.tool_set_by_id",
"wm.context_set_value",
"screen.animation_step",
})
# Operator properties holding filesystem paths. Never recorded.
_PATH_PROPERTY_NAMES = frozenset({
"filepath",
"filename",
"directory",
"filepath_raw",
"relpath",
})
_PATH_PROPERTY_SUBSTRINGS = ("filepath", "filename", "directory", "_dir", "path")
MAX_OPERATOR_PROPERTY_CHARS = 200
# depsgraph_update_post fires on every scene update, many times per second
# during interactive drags.
EDIT_POLL_MIN_INTERVAL = 0.1
def _is_path_property(identifier):
"""True if an operator property likely holds a filesystem path."""
lowered = identifier.lower()
if lowered in _PATH_PROPERTY_NAMES:
return True
return any(token in lowered for token in _PATH_PROPERTY_SUBSTRINGS)
class UserEditRecorder:
"""Buffers human-originated operator and undo events for the MCP server.
Anything that happens while an agent command is running is attributed to
the agent, not the human; `agent_command()` brackets that window.
"""
def __init__(self):
self._events = deque(maxlen=MAX_EDIT_EVENTS)
self._agent_depth = 0
self._last_operator_count = 0
self._seen_baseline = False
self._last_poll_time = 0.0
@contextmanager
def agent_command(self):
"""Suppress capture for the duration of an agent-issued command."""
self._agent_depth += 1
try:
yield
finally:
self._agent_depth = max(0, self._agent_depth - 1)
self._resync_operator_baseline()
@property
def _suppressed(self):
return self._agent_depth > 0
def _operator_stack(self):
try:
return list(bpy.context.window_manager.operators)
except Exception:
return []
def _resync_operator_baseline(self):
self._last_operator_count = len(self._operator_stack())
self._seen_baseline = True
def poll_operators(self, now=None):
"""Emit rows for operators run since the last poll. Main thread only.
Throttled to EDIT_POLL_MIN_INTERVAL.
"""
if self._suppressed:
return
now = time.time() if now is None else now
if (now - self._last_poll_time) < EDIT_POLL_MIN_INTERVAL:
return
self._last_poll_time = now
stack = self._operator_stack()
count = len(stack)
# First poll only establishes a baseline.
if not self._seen_baseline:
self._last_operator_count = count
self._seen_baseline = True
return
if count <= self._last_operator_count:
# Unchanged, or shrank because of an undo. Hold the high-water
# mark so a later redo does not replay emitted operators.
return
for op in stack[self._last_operator_count:count]:
self._record_operator(op)
self._last_operator_count = count
def _record_operator(self, op):
try:
bl_idname = getattr(op, "bl_idname", None)
if not bl_idname:
return
# bl_idname is UPPER_CASE_OT_form; normalise to bpy.ops form.
normalized = bl_idname.lower().replace("_ot_", ".", 1)
if normalized in _IGNORED_OPERATORS:
return
self._events.append({
"kind": "operator",
"bl_idname": normalized,
"name": getattr(op, "name", None),
"properties": self._operator_properties(op),
"timestamp": time.time(),
})
except Exception as e:
print(f"Manual edit capture: failed to record operator: {e}")
@staticmethod
def _operator_properties(op):
"""Best-effort scalar snapshot of an operator's resolved properties."""
props = {}