graphcore-kernel 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (343) hide show
  1. graphcore/__init__.py +5 -0
  2. graphcore/agent_frontend/__init__.py +8 -0
  3. graphcore/agent_frontend/api.py +69 -0
  4. graphcore/agent_frontend/base/__init__.py +11 -0
  5. graphcore/agent_frontend/base/views.py +167 -0
  6. graphcore/agent_frontend/client.py +31 -0
  7. graphcore/agent_frontend/context.py +157 -0
  8. graphcore/agent_frontend/errors.py +12 -0
  9. graphcore/agent_frontend/loading.py +54 -0
  10. graphcore/agent_frontend/registry.py +42 -0
  11. graphcore/agent_frontend/render.py +207 -0
  12. graphcore/agent_frontend/server.py +103 -0
  13. graphcore/agent_frontend/signatures.py +35 -0
  14. graphcore/agent_frontend/testing.py +45 -0
  15. graphcore/agent_frontend/tests/__init__.py +0 -0
  16. graphcore/agent_frontend/tests/fakes.py +114 -0
  17. graphcore/agent_frontend/tests/test_frontend.py +447 -0
  18. graphcore/agent_frontend/tests/test_loading.py +83 -0
  19. graphcore/agent_frontend/tests/test_server.py +109 -0
  20. graphcore/agent_frontend/tools.py +137 -0
  21. graphcore/api/__init__.py +4 -0
  22. graphcore/api/graph_api.py +378 -0
  23. graphcore/api/predicate_codec.py +81 -0
  24. graphcore/api/tests/__init__.py +0 -0
  25. graphcore/api/tests/test_changed_entities.py +109 -0
  26. graphcore/api/tests/test_graph_api.py +290 -0
  27. graphcore/api/tests/test_graph_api_access.py +94 -0
  28. graphcore/api/tests/test_graph_api_grants.py +90 -0
  29. graphcore/api/tests/test_predicate_codec.py +83 -0
  30. graphcore/api/tests/test_subtree_query.py +79 -0
  31. graphcore/apps.py +71 -0
  32. graphcore/auth/__init__.py +1 -0
  33. graphcore/auth/authn/README.md +178 -0
  34. graphcore/auth/authn/__init__.py +3 -0
  35. graphcore/auth/authn/authenticator.py +120 -0
  36. graphcore/auth/authn/onboarding.py +105 -0
  37. graphcore/auth/authn/principals.py +20 -0
  38. graphcore/auth/authn/resource_metadata.py +43 -0
  39. graphcore/auth/authn/service_accounts.py +96 -0
  40. graphcore/auth/authn/testing.py +96 -0
  41. graphcore/auth/authn/tests/__init__.py +0 -0
  42. graphcore/auth/authn/tests/test_authenticator.py +145 -0
  43. graphcore/auth/authn/tests/test_onboarding.py +145 -0
  44. graphcore/auth/authn/tests/test_service_accounts.py +180 -0
  45. graphcore/auth/authn/users.py +59 -0
  46. graphcore/auth/authz/__init__.py +0 -0
  47. graphcore/auth/authz/access_port.py +120 -0
  48. graphcore/auth/authz/adapter/__init__.py +0 -0
  49. graphcore/auth/authz/adapter/default_access_adapter.py +556 -0
  50. graphcore/auth/authz/adapter/tests/__init__.py +0 -0
  51. graphcore/auth/authz/adapter/tests/test_default_adapter.py +543 -0
  52. graphcore/auth/authz/adapter/tests/test_entity_write_hooks.py +207 -0
  53. graphcore/auth/authz/adapter/tests/test_group_types.py +70 -0
  54. graphcore/auth/authz/adapter/tests/test_sync_support.py +209 -0
  55. graphcore/auth/authz/defaults.py +26 -0
  56. graphcore/auth/authz/kernel_policy.py +191 -0
  57. graphcore/auth/authz/kernel_writes.py +31 -0
  58. graphcore/auth/authz/lookups.py +25 -0
  59. graphcore/auth/authz/policy.py +403 -0
  60. graphcore/auth/authz/tests/__init__.py +0 -0
  61. graphcore/auth/authz/tests/test_can_contain.py +150 -0
  62. graphcore/auth/authz/tests/test_contained_by.py +167 -0
  63. graphcore/auth/authz/tests/test_creation.py +391 -0
  64. graphcore/auth/authz/tests/test_delete_permission.py +82 -0
  65. graphcore/auth/authz/tests/test_granted_to_me.py +160 -0
  66. graphcore/auth/authz/tests/test_integration.py +637 -0
  67. graphcore/auth/authz/tests/test_invites.py +184 -0
  68. graphcore/auth/authz/tests/test_kernel_policy.py +140 -0
  69. graphcore/auth/authz/tests/test_lockout.py +132 -0
  70. graphcore/auth/authz/tests/test_policy.py +329 -0
  71. graphcore/auth/authz/tests/test_primitives.py +73 -0
  72. graphcore/auth/authz/tests/test_principal_creation.py +62 -0
  73. graphcore/bootstrap/__init__.py +0 -0
  74. graphcore/bootstrap/deployment.py +67 -0
  75. graphcore/bootstrap/signals.py +16 -0
  76. graphcore/bootstrap/tests/__init__.py +0 -0
  77. graphcore/bootstrap/tests/test_deployment_seed.py +154 -0
  78. graphcore/broadcast/__init__.py +4 -0
  79. graphcore/broadcast/broadcaster.py +201 -0
  80. graphcore/broadcast/channels.py +56 -0
  81. graphcore/broadcast/tests/__init__.py +0 -0
  82. graphcore/broadcast/tests/test_broadcaster.py +444 -0
  83. graphcore/celery.py +14 -0
  84. graphcore/docs/AGENT_FRONTEND_TDD.md +389 -0
  85. graphcore/docs/ARCHITECTURE_PRINCIPLES.md +152 -0
  86. graphcore/docs/AUTHORIZATION_TECHNICAL_TDD.md +1379 -0
  87. graphcore/docs/ENTITY_REFERENCE_TDD.md +561 -0
  88. graphcore/docs/GRAPHAPI_FRONT_DOOR.md +173 -0
  89. graphcore/docs/RUNTIME.md +90 -0
  90. graphcore/docs/SCHEDULING_TDD.md +244 -0
  91. graphcore/docs/STRATEGY_EXECUTION_TDD.md +1043 -0
  92. graphcore/docs/VIEW_ENTITY_TDD.md +522 -0
  93. graphcore/docs/VIEW_SYSTEM_TDD.md +307 -0
  94. graphcore/docs/__init__.py +0 -0
  95. graphcore/docs/doc_topics.py +97 -0
  96. graphcore/docs/docs_discovery.py +64 -0
  97. graphcore/docs/public_api.py +56 -0
  98. graphcore/domain/__init__.py +0 -0
  99. graphcore/domain/entity/Entity.py +204 -0
  100. graphcore/domain/entity/__init__.py +0 -0
  101. graphcore/domain/entity/deployment/Deployment.py +25 -0
  102. graphcore/domain/entity/deployment/__init__.py +0 -0
  103. graphcore/domain/entity/grant/Grant.py +31 -0
  104. graphcore/domain/entity/grant/__init__.py +0 -0
  105. graphcore/domain/entity/group/Group.py +48 -0
  106. graphcore/domain/entity/group/README.md +88 -0
  107. graphcore/domain/entity/group/__init__.py +0 -0
  108. graphcore/domain/entity/invite/Invite.py +31 -0
  109. graphcore/domain/entity/invite/__init__.py +0 -0
  110. graphcore/domain/entity/request_template/RequestTemplate.py +48 -0
  111. graphcore/domain/entity/request_template/__init__.py +0 -0
  112. graphcore/domain/entity/request_template/tests/__init__.py +0 -0
  113. graphcore/domain/entity/request_template/tests/test_request_template.py +52 -0
  114. graphcore/domain/entity/service_account/ServiceAccount.py +41 -0
  115. graphcore/domain/entity/service_account/__init__.py +0 -0
  116. graphcore/domain/entity/strategy_request/StrategyRequest.py +61 -0
  117. graphcore/domain/entity/strategy_request/__init__.py +0 -0
  118. graphcore/domain/entity/strategy_request/tests/__init__.py +0 -0
  119. graphcore/domain/entity/strategy_request/tests/test_strategy_request_entity.py +35 -0
  120. graphcore/domain/entity/tests/__init__.py +0 -0
  121. graphcore/domain/entity/tests/test_entity.py +227 -0
  122. graphcore/domain/entity/tests/test_grant_group_entities.py +36 -0
  123. graphcore/domain/entity/tests/test_write_once_fields.py +98 -0
  124. graphcore/domain/entity/user/User.py +39 -0
  125. graphcore/domain/entity/user/__init__.py +0 -0
  126. graphcore/domain/entity/user/tests/__init__.py +0 -0
  127. graphcore/domain/entity/user/tests/test_user_entity.py +33 -0
  128. graphcore/domain/entity/view/View.py +37 -0
  129. graphcore/domain/entity/view/__init__.py +0 -0
  130. graphcore/domain/entity/view/position.py +78 -0
  131. graphcore/domain/entity/view/tests/__init__.py +0 -0
  132. graphcore/domain/entity/view/tests/test_position.py +71 -0
  133. graphcore/domain/entity/view/tests/test_view_entity.py +134 -0
  134. graphcore/domain/strategy/BaseStrategy.py +759 -0
  135. graphcore/domain/strategy/DeploymentStrategies.py +55 -0
  136. graphcore/domain/strategy/GrantStrategies.py +189 -0
  137. graphcore/domain/strategy/GroupStrategies.py +193 -0
  138. graphcore/domain/strategy/InviteStrategies.py +84 -0
  139. graphcore/domain/strategy/RequestTemplateStrategies.py +126 -0
  140. graphcore/domain/strategy/ViewStrategies.py +219 -0
  141. graphcore/domain/strategy/__init__.py +0 -0
  142. graphcore/domain/strategy/runner.py +84 -0
  143. graphcore/domain/strategy/session.py +56 -0
  144. graphcore/domain/strategy/tests/BaseStrategyTest.py +167 -0
  145. graphcore/domain/strategy/tests/__init__.py +0 -0
  146. graphcore/domain/strategy/tests/test_BaseStrategies.py +870 -0
  147. graphcore/domain/strategy/tests/test_grant_strategies.py +245 -0
  148. graphcore/domain/strategy/tests/test_group_strategies.py +99 -0
  149. graphcore/domain/strategy/tests/test_runner.py +220 -0
  150. graphcore/domain/strategy/tests/test_strategy_locks.py +446 -0
  151. graphcore/domain/strategy/tests/test_utils.py +95 -0
  152. graphcore/domain/strategy/tests/test_view_strategies.py +436 -0
  153. graphcore/errors.py +145 -0
  154. graphcore/execution/README.md +97 -0
  155. graphcore/execution/StrategyExecutorService.py +333 -0
  156. graphcore/execution/__init__.py +0 -0
  157. graphcore/execution/dispatcher.py +19 -0
  158. graphcore/execution/environments/__init__.py +0 -0
  159. graphcore/execution/environments/celery.py +59 -0
  160. graphcore/execution/environments/in_process.py +55 -0
  161. graphcore/execution/local_session.py +117 -0
  162. graphcore/execution/redis_run_events.py +74 -0
  163. graphcore/execution/requests.py +22 -0
  164. graphcore/execution/run_events.py +85 -0
  165. graphcore/execution/strategy_context.py +54 -0
  166. graphcore/execution/tasks.py +34 -0
  167. graphcore/execution/tests/__init__.py +5 -0
  168. graphcore/execution/tests/contract.py +171 -0
  169. graphcore/execution/tests/support.py +310 -0
  170. graphcore/execution/tests/test_dispatchers.py +76 -0
  171. graphcore/execution/tests/test_executor.py +368 -0
  172. graphcore/execution/tests/test_local_session.py +95 -0
  173. graphcore/execution/tests/test_reconcile_runs.py +134 -0
  174. graphcore/execution/tests/test_run_events.py +106 -0
  175. graphcore/execution/tests/test_strategy_context.py +62 -0
  176. graphcore/gateway/__init__.py +1 -0
  177. graphcore/gateway/remote.py +35 -0
  178. graphcore/gateway/tests/__init__.py +0 -0
  179. graphcore/gateway/tests/test_remote.py +30 -0
  180. graphcore/graph/EntityService.py +710 -0
  181. graphcore/graph/__init__.py +0 -0
  182. graphcore/graph/entity_cache.py +152 -0
  183. graphcore/graph/tests/__init__.py +4 -0
  184. graphcore/graph/tests/test_EntityService.py +908 -0
  185. graphcore/graph/tests/test_EntityService_list.py +170 -0
  186. graphcore/graph/tests/test_EntityService_model_resolution.py +339 -0
  187. graphcore/graph/tests/test_EntityService_referrers.py +236 -0
  188. graphcore/graph/tests/test_EntityService_routing.py +119 -0
  189. graphcore/graph/tests/test_dependent_on.py +141 -0
  190. graphcore/graph/tests/test_engine_is_type_agnostic.py +25 -0
  191. graphcore/graph/tests/test_engine_resolves_read_permission.py +93 -0
  192. graphcore/graph/tests/test_entity_cache.py +159 -0
  193. graphcore/graph/tests/test_null_entity_cache.py +12 -0
  194. graphcore/management/__init__.py +0 -0
  195. graphcore/management/commands/__init__.py +0 -0
  196. graphcore/management/commands/dev_reset.py +18 -0
  197. graphcore/management/commands/graphcore_createadmin.py +65 -0
  198. graphcore/management/commands/graphcore_policy.py +59 -0
  199. graphcore/management/commands/graphcore_status.py +98 -0
  200. graphcore/management/tests/__init__.py +0 -0
  201. graphcore/management/tests/test_createadmin.py +78 -0
  202. graphcore/management/tests/test_policy_command.py +46 -0
  203. graphcore/management/tests/test_status_command.py +85 -0
  204. graphcore/migrations/0001_initial.py +186 -0
  205. graphcore/migrations/0002_invite.py +26 -0
  206. graphcore/migrations/__init__.py +0 -0
  207. graphcore/models.py +11 -0
  208. graphcore/persistence/ENTITY_REPOSITORY_TECHNICAL_TDD.md +396 -0
  209. graphcore/persistence/__init__.py +6 -0
  210. graphcore/persistence/django/__init__.py +0 -0
  211. graphcore/persistence/django/backends.py +43 -0
  212. graphcore/persistence/django/bindings.py +28 -0
  213. graphcore/persistence/django/cache.py +38 -0
  214. graphcore/persistence/django/compiler.py +214 -0
  215. graphcore/persistence/django/identity.py +18 -0
  216. graphcore/persistence/django/models.py +252 -0
  217. graphcore/persistence/django/repository.py +525 -0
  218. graphcore/persistence/django/tests/__init__.py +0 -0
  219. graphcore/persistence/django/tests/test_backends.py +68 -0
  220. graphcore/persistence/django/tests/test_compiler.py +269 -0
  221. graphcore/persistence/django/tests/test_repository.py +472 -0
  222. graphcore/persistence/django/tests/test_shared_column.py +120 -0
  223. graphcore/persistence/django/tests/test_threads.py +50 -0
  224. graphcore/persistence/django/tests/test_update_shape.py +175 -0
  225. graphcore/persistence/django/threads.py +38 -0
  226. graphcore/persistence/repository.py +172 -0
  227. graphcore/persistence/tests/__init__.py +0 -0
  228. graphcore/persistence/tests/contract.py +688 -0
  229. graphcore/persistence/tests/evaluate.py +51 -0
  230. graphcore/persistence/tests/fixtures.py +32 -0
  231. graphcore/persistence/tests/memory.py +263 -0
  232. graphcore/persistence/tests/test_memory_repository.py +10 -0
  233. graphcore/persistence/tests/test_query_types.py +127 -0
  234. graphcore/public/__init__.py +9 -0
  235. graphcore/public/api.py +9 -0
  236. graphcore/public/apps.py +10 -0
  237. graphcore/public/auth/__init__.py +1 -0
  238. graphcore/public/auth/grants.py +7 -0
  239. graphcore/public/auth/onboarding.py +8 -0
  240. graphcore/public/auth/perms.py +7 -0
  241. graphcore/public/auth/policy.py +10 -0
  242. graphcore/public/auth/roles.py +8 -0
  243. graphcore/public/auth/subjects.py +7 -0
  244. graphcore/public/entities/__init__.py +32 -0
  245. graphcore/public/errors.py +19 -0
  246. graphcore/public/persistence/__init__.py +44 -0
  247. graphcore/public/persistence/django.py +24 -0
  248. graphcore/public/scheduling.py +23 -0
  249. graphcore/public/strategies/__init__.py +85 -0
  250. graphcore/public/test_settings.py +16 -0
  251. graphcore/public/testing.py +47 -0
  252. graphcore/registry/EntityDirectory.py +246 -0
  253. graphcore/registry/README.md +147 -0
  254. graphcore/registry/StrategyDirectory.py +308 -0
  255. graphcore/registry/TYPE_METADATA_PLACEMENT.md +66 -0
  256. graphcore/registry/__init__.py +0 -0
  257. graphcore/registry/app_discovery.py +108 -0
  258. graphcore/registry/decorators.py +77 -0
  259. graphcore/registry/discovery.py +111 -0
  260. graphcore/registry/registry.py +79 -0
  261. graphcore/registry/tests/__init__.py +0 -0
  262. graphcore/registry/tests/test_agent_frontend_discovery.py +56 -0
  263. graphcore/registry/tests/test_app_config.py +36 -0
  264. graphcore/registry/tests/test_discovery.py +147 -0
  265. graphcore/registry/tests/test_entity_directory_storage.py +73 -0
  266. graphcore/registry/tests/test_import_package.py +87 -0
  267. graphcore/registry/tests/test_principal_flag.py +67 -0
  268. graphcore/registry/tests/test_strategy_directory.py +29 -0
  269. graphcore/routes/__init__.py +116 -0
  270. graphcore/routes/tests/__init__.py +0 -0
  271. graphcore/routes/tests/test_routes.py +90 -0
  272. graphcore/runtime.py +243 -0
  273. graphcore/scheduling/__init__.py +0 -0
  274. graphcore/scheduling/beat_scheduler.py +164 -0
  275. graphcore/scheduling/beat_tasks.py +63 -0
  276. graphcore/scheduling/scheduler.py +37 -0
  277. graphcore/scheduling/tests/__init__.py +0 -0
  278. graphcore/scheduling/tests/contract.py +136 -0
  279. graphcore/scheduling/tests/memory.py +42 -0
  280. graphcore/scheduling/tests/test_beat_scheduler.py +87 -0
  281. graphcore/scheduling/tests/test_memory_scheduler.py +15 -0
  282. graphcore/scheduling/tests/test_ticks.py +143 -0
  283. graphcore/tasks.py +9 -0
  284. graphcore/test_settings.py +78 -0
  285. graphcore/testing/__init__.py +0 -0
  286. graphcore/testing/case.py +112 -0
  287. graphcore/testing/runner.py +32 -0
  288. graphcore/testing/settings.py +26 -0
  289. graphcore/testing/tests/__init__.py +0 -0
  290. graphcore/testing/tests/agent_view_fixture.py +19 -0
  291. graphcore/testing/tests/test_case_and_runner.py +219 -0
  292. graphcore/testing/tests/test_settings_for_apps.py +50 -0
  293. graphcore/tests/__init__.py +0 -0
  294. graphcore/tests/ids.py +14 -0
  295. graphcore/tests/public_api_manifest.py +102 -0
  296. graphcore/tests/runs.py +7 -0
  297. graphcore/tests/test_app_discovery.py +90 -0
  298. graphcore/tests/test_composition_boundaries.py +231 -0
  299. graphcore/tests/test_docs_discovery.py +108 -0
  300. graphcore/tests/test_no_print.py +70 -0
  301. graphcore/tests/test_packaging.py +64 -0
  302. graphcore/tests/test_public_api_boundaries.py +229 -0
  303. graphcore/tests/test_public_api_contract.py +62 -0
  304. graphcore/tests/test_public_api_docs.py +28 -0
  305. graphcore/tests/test_runtime.py +42 -0
  306. graphcore/tests/test_shared_type_boundaries.py +128 -0
  307. graphcore/tests/test_shared_types.py +144 -0
  308. graphcore/tests/test_test_settings.py +45 -0
  309. graphcore/transport/__init__.py +0 -0
  310. graphcore/transport/agent_asgi.py +68 -0
  311. graphcore/transport/agent_client.py +85 -0
  312. graphcore/transport/channel_layer.py +68 -0
  313. graphcore/transport/consumers.py +507 -0
  314. graphcore/transport/routing.py +6 -0
  315. graphcore/transport/tests/__init__.py +0 -0
  316. graphcore/transport/tests/test_agent_client.py +31 -0
  317. graphcore/transport/tests/test_api_views.py +733 -0
  318. graphcore/transport/tests/test_channel_layer.py +96 -0
  319. graphcore/transport/tests/test_consumers.py +963 -0
  320. graphcore/transport/tests/test_resource_metadata.py +67 -0
  321. graphcore/transport/urls.py +29 -0
  322. graphcore/transport/views.py +358 -0
  323. graphcore/types/__init__.py +4 -0
  324. graphcore/types/access.py +114 -0
  325. graphcore/types/api.py +76 -0
  326. graphcore/types/entities.py +100 -0
  327. graphcore/types/entity_id.py +85 -0
  328. graphcore/types/execution.py +41 -0
  329. graphcore/types/identity.py +20 -0
  330. graphcore/types/onboarding.py +20 -0
  331. graphcore/types/query.py +116 -0
  332. graphcore/types/schedules.py +91 -0
  333. graphcore/types/strategy.py +73 -0
  334. graphcore/types/tests/__init__.py +0 -0
  335. graphcore/types/tests/test_entity_id.py +50 -0
  336. graphcore/urls.py +5 -0
  337. graphcore_kernel-0.1.0.dist-info/METADATA +94 -0
  338. graphcore_kernel-0.1.0.dist-info/RECORD +343 -0
  339. graphcore_kernel-0.1.0.dist-info/WHEEL +5 -0
  340. graphcore_kernel-0.1.0.dist-info/entry_points.txt +2 -0
  341. graphcore_kernel-0.1.0.dist-info/licenses/LICENSE +202 -0
  342. graphcore_kernel-0.1.0.dist-info/licenses/NOTICE +2 -0
  343. graphcore_kernel-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,207 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from dataclasses import dataclass
5
+ from typing import Any, Optional
6
+
7
+ from graphcore.agent_frontend import signatures
8
+ from graphcore.agent_frontend.api import AgentView, ToolSpec
9
+ from graphcore.agent_frontend.client import GraphClient
10
+ from graphcore.agent_frontend.context import DEFAULT_QUERY_MAX, Context, Placement, Reads, label_of
11
+ from graphcore.agent_frontend.errors import AgentError, RenderTooLarge
12
+ from graphcore.agent_frontend.registry import AgentRegistry
13
+ from graphcore.errors import NotFound
14
+ from graphcore.types.identity import Principal
15
+
16
+ DEFAULT_MAX_CHARS = 60000
17
+ _DESCRIPTION_CHARS = 120
18
+
19
+
20
+ @dataclass
21
+ class Frontend:
22
+ client: GraphClient
23
+ registry: AgentRegistry
24
+ max_chars: int = int(os.environ.get('GRAPHCORE_AGENT_RENDER_MAX_CHARS', DEFAULT_MAX_CHARS))
25
+ query_max: int = int(os.environ.get('GRAPHCORE_AGENT_QUERY_MAX', DEFAULT_QUERY_MAX))
26
+
27
+
28
+ @dataclass
29
+ class ResolvedTool:
30
+ name: str
31
+ description: Optional[str]
32
+ schema: dict
33
+ spec: ToolSpec
34
+
35
+ @property
36
+ def signature(self) -> str:
37
+ return signatures.signature(
38
+ self.name, self.schema, self.description, target_param=self.takes_target,
39
+ )
40
+
41
+ @property
42
+ def takes_target(self) -> bool:
43
+ return self.spec.fn is None and self.spec.bind is None and self.spec.takes_target
44
+
45
+ def full_schema(self) -> dict:
46
+ if not self.takes_target:
47
+ return self.schema
48
+ schema = dict(self.schema)
49
+ schema['properties'] = {'target': {'type': 'string'}, **schema.get('properties', {})}
50
+ schema['required'] = ['target', *schema.get('required', [])]
51
+ return schema
52
+
53
+
54
+ @dataclass
55
+ class Rendered:
56
+ address: str
57
+ text: str
58
+ version: str
59
+ tools: list[ResolvedTool]
60
+ entity: Any
61
+
62
+
63
+ @dataclass
64
+ class _Body:
65
+ title: str
66
+ text: str
67
+ tools: list[ResolvedTool]
68
+ entity: Any
69
+
70
+
71
+ def _one_line(description: Optional[str]) -> Optional[str]:
72
+ if not description:
73
+ return None
74
+ line = ' '.join(description.split())
75
+ return line if len(line) <= _DESCRIPTION_CHARS else line[:_DESCRIPTION_CHARS - 1] + '…'
76
+
77
+
78
+ async def _placeholder(ctx: Context, entity: Any = None) -> list:
79
+ return ["No agent view renders this address. Use `find` to look for entities."]
80
+
81
+
82
+ _PLACEHOLDER = AgentView('placeholder', _placeholder)
83
+
84
+
85
+ async def _choose(fe: Frontend, ctx: Context, view_name: str, entity_id: Optional[str]) -> tuple[AgentView, Any]:
86
+ """For `entity`, the view whose `default_for` has the entity's type; then the view the route
87
+ names; then, for a route with an entity, the view named `entity`."""
88
+ entity = await ctx.get(entity_id) if entity_id else None
89
+ if entity_id and entity is None:
90
+ raise AgentError('NotFound', f"{ctx.address} does not exist or is not readable")
91
+ view = fe.registry.default_for(entity.entity_type_id) if view_name == 'entity' else None
92
+ view = view or fe.registry.by_name(view_name)
93
+ if view is None and entity is not None:
94
+ view = fe.registry.by_name('entity')
95
+ return view or _PLACEHOLDER, entity
96
+
97
+
98
+ async def _tools(fe: Frontend, ctx: Context, view: AgentView, entity: Any) -> list[ResolvedTool]:
99
+ specs = list(await view.tools(ctx, entity)) if view.tools else []
100
+ info = fe.client.strategy_info()
101
+ untargeted = {s['name'] for s in fe.client.deployment_strategies()}
102
+ resolved: dict[str, ResolvedTool] = {}
103
+ for spec in specs:
104
+ if spec.fn is not None:
105
+ tool = ResolvedTool(spec.name, spec.description, spec.schema or {}, spec)
106
+ else:
107
+ if spec.strategy not in info:
108
+ continue
109
+ if not spec.takes_target and spec.bind is None and spec.strategy not in untargeted:
110
+ continue
111
+ if spec.bind is not None:
112
+ bound = await ctx.get(spec.bind)
113
+ if bound is None or spec.strategy not in {
114
+ s['name'] for s in fe.client.type_strategies(bound.entity_type_id)
115
+ }:
116
+ continue
117
+ strategy = info[spec.strategy]
118
+ tool = ResolvedTool(
119
+ spec.name, spec.description or _one_line(strategy.get('description')),
120
+ strategy.get('schema') or {}, spec,
121
+ )
122
+ resolved.setdefault(tool.name, tool)
123
+ return list(resolved.values())
124
+
125
+
126
+ async def _label_line(fe: Frontend, ctx: Context, address: str) -> Optional[str]:
127
+ try:
128
+ resolved = fe.client.resolve(address)
129
+ except NotFound:
130
+ raise AgentError('NotFound', f"no route matches {address!r}; start from open('/')")
131
+ if resolved['entity_id'] is None:
132
+ return f"- {resolved['view_name']} · {address}"
133
+ entity = await ctx.get(resolved['entity_id'])
134
+ if entity is None:
135
+ return None
136
+ return f"- {label_of(entity)} · {entity.entity_type_id} · {address}"
137
+
138
+
139
+ async def _expand(
140
+ fe: Frontend, principal: Principal, ctx: Context, parts: list, reads: Reads, stack: tuple,
141
+ ) -> str:
142
+ blocks: list[str] = []
143
+ lines: list[str] = []
144
+
145
+ def flush() -> None:
146
+ if lines:
147
+ blocks.append('\n'.join(lines))
148
+ lines.clear()
149
+
150
+ for part in parts:
151
+ if isinstance(part, Placement) and not part.full:
152
+ line = await _label_line(fe, ctx, part.address)
153
+ if line:
154
+ lines.append(line)
155
+ elif isinstance(part, Placement):
156
+ flush()
157
+ child = await _render_body(fe, principal, part.address, reads, stack)
158
+ if child.entity is not None:
159
+ heading = f"### {label_of(child.entity)} · {child.entity.entity_type_id} · {part.address}"
160
+ else:
161
+ heading = f"### {child.title} · {part.address}"
162
+ blocks.append(f"{heading}\n{child.text}")
163
+ else:
164
+ flush()
165
+ blocks.append(str(part))
166
+ flush()
167
+ return '\n\n'.join(block for block in blocks if block)
168
+
169
+
170
+ async def _render_body(
171
+ fe: Frontend, principal: Principal, address: str, reads: Reads, stack: tuple = (),
172
+ with_tools: bool = False,
173
+ ) -> _Body:
174
+ if address in stack:
175
+ raise RenderTooLarge(address, ': full placements form a cycle')
176
+ try:
177
+ resolved = fe.client.resolve(address)
178
+ except NotFound:
179
+ raise AgentError('NotFound', f"no route matches {address!r}; start from open('/')")
180
+ ctx = Context(principal, address, None, fe.client, reads, fe.registry, fe.query_max)
181
+ view, entity = await _choose(fe, ctx, resolved['view_name'], resolved['entity_id'])
182
+ ctx.entity = entity
183
+ result = await (view.fn(ctx, entity) if entity is not None else view.fn(ctx))
184
+ parts = result if isinstance(result, list) else [result]
185
+ text = await _expand(fe, principal, ctx, parts, reads, stack + (address,))
186
+ title = (
187
+ f"{label_of(entity)} · {entity.entity_type_id}" if entity is not None
188
+ else ('Home' if resolved['view_name'] == 'home' else resolved['view_name'])
189
+ )
190
+ tools = await _tools(fe, ctx, view, entity) if with_tools else []
191
+ return _Body(title, text, tools, entity)
192
+
193
+
194
+ async def render(fe: Frontend, principal: Principal, address: str) -> Rendered:
195
+ address = '/' + address.strip('/') if address.strip('/') else '/'
196
+ reads = Reads()
197
+ body = await _render_body(fe, principal, address, reads, with_tools=True)
198
+ version = reads.version()
199
+ out = [f"# {body.title}", f"address: {address} · version: {version}"]
200
+ if body.text:
201
+ out.append('\n' + body.text)
202
+ if body.tools:
203
+ out.append('\n## Tools\n' + '\n'.join(f"- {tool.signature}" for tool in body.tools))
204
+ text = '\n'.join(out)
205
+ if len(text) > fe.max_chars:
206
+ raise RenderTooLarge(address, f" ({len(text)} characters; the limit is {fe.max_chars})")
207
+ return Rendered(address, text, version, body.tools, body.entity)
@@ -0,0 +1,103 @@
1
+ """The MCP endpoint: four fixed tools over a `Frontend`, stateless, bearer-authenticated."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Callable, Optional, Sequence
5
+
6
+ from mcp.server.mcpserver import Context, MCPServer
7
+ from mcp.server.mcpserver.exceptions import ToolError
8
+ from mcp.server.transport_security import TransportSecuritySettings
9
+ from starlette.middleware.cors import CORSMiddleware
10
+ from starlette.responses import JSONResponse
11
+
12
+ from graphcore.agent_frontend import tools
13
+ from graphcore.agent_frontend.client import GraphClient
14
+ from graphcore.agent_frontend.errors import AgentError
15
+ from graphcore.agent_frontend.registry import AgentRegistry
16
+ from graphcore.agent_frontend.render import Frontend
17
+
18
+ INSTRUCTIONS = """\
19
+ This server presents a GraphCore deployment as addressed places. Start with open("/").
20
+ Every place is a Markdown page: its content, its address, a version, and a Tools list.
21
+ - open(at): read a place. Addresses look like /, /notes, /e/<backend>/<local>.
22
+ - call(at, tool, params): run a tool listed under that place's Tools. Pass seen_version
23
+ (the version you last read) so a write based on out-of-date content is refused.
24
+ - find(type, predicate): list entities of a type, optionally filtered by field equality.
25
+ - act(strategy, target, params): run a strategy directly when no place lists it as a tool.
26
+ Reads and writes run as the user whose token you connected with.
27
+ """
28
+
29
+
30
+ def _principal(ctx: Context):
31
+ return ctx.request_context.request.state.principal
32
+
33
+
34
+ def _guard(coro_fn):
35
+ async def run(*args, **kwargs):
36
+ try:
37
+ return await coro_fn(*args, **kwargs)
38
+ except AgentError as exc:
39
+ raise ToolError(f"{exc.code}: {exc.message}")
40
+ return run
41
+
42
+
43
+ class _BearerAuth:
44
+ def __init__(self, app, client: GraphClient, challenge: Callable[[dict], str]):
45
+ self.app = app
46
+ self.client = client
47
+ self.challenge = challenge
48
+
49
+ async def __call__(self, scope, receive, send):
50
+ if scope['type'] != 'http':
51
+ return await self.app(scope, receive, send)
52
+ headers = dict(scope['headers'])
53
+ value = headers.get(b'authorization', b'').decode()
54
+ scheme, _, token = value.partition(' ')
55
+ principal = await self.client.authenticate(token) if scheme.lower() == 'bearer' else None
56
+ if principal is None:
57
+ response = JSONResponse({'error': 'unauthorized'}, 401, {'WWW-Authenticate': self.challenge(scope)})
58
+ return await response(scope, receive, send)
59
+ scope.setdefault('state', {})['principal'] = principal
60
+ await self.app(scope, receive, send)
61
+
62
+
63
+ def create_app(
64
+ client: GraphClient, registry: AgentRegistry, path: str = '/mcp', allowed_origins: Sequence[str] = (),
65
+ challenge: Callable[[dict], str] = lambda scope: 'Bearer',
66
+ ):
67
+ """``challenge`` builds the 401's ``WWW-Authenticate`` value from the ASGI scope."""
68
+ fe = Frontend(client, registry)
69
+ mcp = MCPServer('graphcore', instructions=INSTRUCTIONS)
70
+
71
+ @mcp.tool(description='Read a place. Returns Markdown with its address, version and Tools.')
72
+ async def open(at: str, ctx: Context, version: Optional[str] = None) -> str:
73
+ return await _guard(tools.open_)(fe, _principal(ctx), at, version)
74
+
75
+ @mcp.tool(description='List entities of a type; predicate maps field to a value or a list of values.')
76
+ async def find(type: str, ctx: Context, predicate: Optional[dict[str, Any]] = None, limit: int = 25) -> str:
77
+ return await _guard(tools.find)(fe, _principal(ctx), type, predicate, limit)
78
+
79
+ @mcp.tool(description="Run a tool listed at a place. Pass seen_version to refuse the write if the place changed.")
80
+ async def call(
81
+ at: str, tool: str, ctx: Context, params: Optional[dict[str, Any]] = None,
82
+ seen_version: Optional[str] = None,
83
+ ) -> str:
84
+ return await _guard(tools.call)(fe, _principal(ctx), at, tool, params, seen_version)
85
+
86
+ @mcp.tool(description='Run a strategy by name, optionally on a target address or entity id.')
87
+ async def act(strategy: str, ctx: Context, target: Optional[str] = None, params: Optional[dict[str, Any]] = None) -> str:
88
+ return await _guard(tools.act)(fe, _principal(ctx), strategy, target, params)
89
+
90
+ app = mcp.streamable_http_app(
91
+ streamable_http_path=path, stateless_http=True, json_response=True,
92
+ # Rebinding protection is off: the SDK default allows only localhost Hosts, and the bearer token gates access. TODO: configurable allowed hosts.
93
+ transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False),
94
+ )
95
+ served = _BearerAuth(app, client, challenge)
96
+ if allowed_origins:
97
+ # Outside the bearer check: a browser's preflight carries no token.
98
+ served = CORSMiddleware(
99
+ served, allow_origins=list(allowed_origins), allow_methods=['GET', 'POST', 'DELETE'],
100
+ allow_headers=['authorization', 'mcp-protocol-version'], expose_headers=['mcp-session-id', 'www-authenticate'],
101
+ )
102
+ served.mcp_app = app
103
+ return served
@@ -0,0 +1,35 @@
1
+ """A JSON schema as a compact tool signature: `name(a: str, b?: int)`."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Optional
5
+
6
+ _SCALARS = {'string': 'str', 'integer': 'int', 'number': 'float', 'boolean': 'bool'}
7
+
8
+
9
+ def _type(prop: dict) -> tuple[str, bool]:
10
+ """The compact type and whether the schema admits null."""
11
+ if 'enum' in prop:
12
+ return '|'.join(str(v) for v in prop['enum']), False
13
+ kind = prop.get('type')
14
+ nullable = False
15
+ if isinstance(kind, list):
16
+ nullable = 'null' in kind
17
+ kinds = [k for k in kind if k != 'null']
18
+ kind = kinds[0] if len(kinds) == 1 else 'json'
19
+ return _SCALARS.get(kind, 'json'), nullable
20
+
21
+
22
+ def params(schema: Optional[dict], target_param: bool = False) -> str:
23
+ schema = schema or {}
24
+ required = set(schema.get('required', []))
25
+ parts = ['target: entity'] if target_param else []
26
+ for name, prop in (schema.get('properties') or {}).items():
27
+ kind, nullable = _type(prop if isinstance(prop, dict) else {})
28
+ optional = nullable or name not in required
29
+ parts.append(f"{name}{'?' if optional else ''}: {kind}")
30
+ return ', '.join(parts)
31
+
32
+
33
+ def signature(name: str, schema: Optional[dict], description: Optional[str], target_param: bool = False) -> str:
34
+ line = f"{name}({params(schema, target_param)})"
35
+ return f"{line} — {description}" if description else line
@@ -0,0 +1,45 @@
1
+ """Opening places and calling their tools from a test, through the same `render`
2
+ and `tools.call` the MCP server runs; `graphcore.public.testing` wires them to a
3
+ test's runtime."""
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ from dataclasses import dataclass
8
+ from functools import lru_cache
9
+ from typing import Optional
10
+
11
+ from graphcore.agent_frontend import tools
12
+ from graphcore.agent_frontend.context import to_address
13
+ from graphcore.agent_frontend.loading import load_registry
14
+ from graphcore.agent_frontend.registry import AgentRegistry
15
+ from graphcore.agent_frontend.render import Frontend, render
16
+ from graphcore.types.identity import Principal
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Place:
21
+ """An agent view as a principal sees it: `text` is exactly what `open`
22
+ returns over `/mcp`; `tools` are the listed tool names, in order."""
23
+
24
+ address: str
25
+ text: str
26
+ version: str
27
+ tools: tuple[str, ...]
28
+
29
+
30
+ @lru_cache
31
+ def cached_registry(modules: tuple[str, ...]) -> AgentRegistry:
32
+ # Loading imports the app modules, and they stay in `sys.modules`.
33
+ return load_registry(modules)
34
+
35
+
36
+ async def open_place(fe: Frontend, principal: Principal, at: str) -> Place:
37
+ rendered = await render(fe, principal, to_address(at))
38
+ return Place(rendered.address, rendered.text, rendered.version, tuple(t.name for t in rendered.tools))
39
+
40
+
41
+ async def call_tool(
42
+ fe: Frontend, principal: Principal, at: str, tool: str, params: Optional[dict] = None,
43
+ seen_version: Optional[str] = None,
44
+ ) -> dict:
45
+ return json.loads(await tools.call(fe, principal, to_address(at), tool, params, seen_version))
File without changes
@@ -0,0 +1,114 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import Any, Optional
3
+
4
+ from graphcore.errors import NotFound
5
+ from graphcore.persistence.tests.evaluate import matches
6
+ from graphcore.types.entities import EntityPage, Tombstone
7
+ from graphcore.types.identity import Principal
8
+ from graphcore.types.query import Predicate
9
+
10
+ PRINCIPAL = Principal('gc://u/alice')
11
+
12
+
13
+ @dataclass
14
+ class FakeEntity:
15
+ entity_id: str
16
+ entity_type_id: str
17
+ version: int = 1
18
+ owner: Optional[str] = None
19
+ parent_id: Optional[str] = None
20
+ fields: dict = field(default_factory=dict)
21
+
22
+ def to_dict(self) -> dict:
23
+ return {'entity_id': self.entity_id, 'entity_type_id': self.entity_type_id,
24
+ 'version': self.version, 'owner': self.owner, 'parent_id': self.parent_id,
25
+ **self.fields}
26
+
27
+
28
+ class FakeGraphClient:
29
+ def __init__(self) -> None:
30
+ self.entities: dict[str, FakeEntity] = {}
31
+ self.route_list = [
32
+ {'pattern': '/', 'view_name': 'home'},
33
+ {'pattern': '/e/{entity}', 'view_name': 'entity'},
34
+ {'pattern': '/notes', 'view_name': 'notes.index'},
35
+ {'pattern': '/notes/{entity}', 'view_name': 'notes.detail'},
36
+ ]
37
+ self.types = ['t.Note', 't.Folder']
38
+ self.strategies = {
39
+ 'CreateNote': {'description': 'Create a note', 'schema': {
40
+ 'type': 'object', 'properties': {'title': {'type': 'string'}}, 'required': ['title']}},
41
+ 'Rename': {'description': 'Rename', 'schema': {
42
+ 'type': 'object', 'properties': {'name': {'type': 'string'}}, 'required': ['name']}},
43
+ }
44
+ self.by_type = {'t.Note': ['Rename'], 't.Folder': []}
45
+ self.deployment = ['CreateNote']
46
+ self.executed: list[tuple] = []
47
+ self.tombstones: set[str] = set()
48
+ self.granted: set[str] = set()
49
+ self.pages_listed = 0
50
+
51
+ def add(self, entity: FakeEntity) -> FakeEntity:
52
+ self.entities[entity.entity_id] = entity
53
+ return entity
54
+
55
+ async def authenticate(self, token: str) -> Optional[Principal]:
56
+ return PRINCIPAL if token == 'good' else None
57
+
58
+ async def get_entity(self, principal, entity_id):
59
+ if entity_id in self.tombstones or entity_id not in self.entities:
60
+ return Tombstone(entity_id, 'not_found')
61
+ return self.entities[entity_id]
62
+
63
+ async def list_children(self, principal, parent_id, type_ids=None, cursor=None, limit=25):
64
+ items = [e for e in self.entities.values()
65
+ if e.parent_id == parent_id and (not type_ids or e.entity_type_id in type_ids)]
66
+ return EntityPage(items[:limit], 'more' if len(items) > limit else None)
67
+
68
+ async def list_entities(
69
+ self, principal, type_ids, parent_id=None, where=None, cursor=None, limit=25, granted_to_me=False,
70
+ ):
71
+ items = sorted((e for e in self.entities.values() if e.entity_type_id in type_ids),
72
+ key=lambda e: e.entity_id)
73
+ if granted_to_me:
74
+ items = [e for e in items if e.entity_id in self.granted]
75
+ if parent_id is not None:
76
+ items = [e for e in items if e.parent_id == parent_id]
77
+ if isinstance(where, Predicate):
78
+ items = [e for e in items if matches(where, e.to_dict())]
79
+ else:
80
+ for key, want in (where or {}).items():
81
+ items = [e for e in items if e.to_dict().get(key) == want]
82
+ if cursor is not None:
83
+ items = [e for e in items if e.entity_id > cursor]
84
+ page = items[:limit]
85
+ self.pages_listed += 1
86
+ return EntityPage(page, page[-1].entity_id if len(items) > limit else None)
87
+
88
+ async def execute(self, principal, strategy_name, target_id, params):
89
+ self.executed.append((strategy_name, target_id, params))
90
+ if strategy_name == 'CreateNote':
91
+ n = len(self.entities) + 1
92
+ self.add(FakeEntity(f'gc://b/{n}', 't.Note', fields={'title': params['title']}))
93
+ if strategy_name == 'Rename':
94
+ e = self.entities[target_id]
95
+ e.fields['name'] = params['name']
96
+ e.version += 1
97
+ return {'status': 'completed', 'ret_val': {'ok': True}}
98
+
99
+ def resolve(self, address):
100
+ if address in ('/', ''):
101
+ return {'view_name': 'home', 'entity_id': None}
102
+ if address.startswith('/e/'):
103
+ return {'view_name': 'entity', 'entity_id': 'gc://' + address[3:]}
104
+ if address == '/notes':
105
+ return {'view_name': 'notes.index', 'entity_id': None}
106
+ if address.startswith('/notes/'):
107
+ return {'view_name': 'notes.detail', 'entity_id': 'gc://' + address[7:]}
108
+ raise NotFound(address)
109
+
110
+ def routes(self): return self.route_list
111
+ def entity_types(self): return self.types
112
+ def type_strategies(self, t): return [{'name': n} for n in self.by_type.get(t, [])]
113
+ def deployment_strategies(self): return [{'name': n} for n in self.deployment]
114
+ def strategy_info(self): return self.strategies