pico-engine 1.9.4 → 1.10.0

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 (186) hide show
  1. package/README.md +13 -5
  2. package/demos/bootstrap/README.md +12 -0
  3. package/demos/bootstrap/com.example.visitors.bootstrap.krl +101 -0
  4. package/demos/bootstrap/com.example.visitors.format.krl +25 -0
  5. package/demos/bootstrap/com.example.visitors.krl +228 -0
  6. package/demos/bootstrap/try-it.md +5 -0
  7. package/demos/child_tasks/README.md +12 -0
  8. package/demos/child_tasks/com.example.task_runner.bootstrap.krl +88 -0
  9. package/demos/child_tasks/com.example.task_runner.krl +139 -0
  10. package/demos/child_tasks/com.example.task_worker.krl +45 -0
  11. package/demos/child_tasks/try-it.md +5 -0
  12. package/demos/collection/README.md +13 -0
  13. package/demos/collection/com.example.collection.bootstrap.krl +148 -0
  14. package/demos/collection/com.example.collection.krl +95 -0
  15. package/demos/collection/com.example.collection.report.krl +93 -0
  16. package/demos/collection/com.example.collection.room.krl +101 -0
  17. package/demos/collection/try-it.md +6 -0
  18. package/demos/echo/README.md +11 -0
  19. package/demos/echo/com.example.echo.bootstrap.krl +84 -0
  20. package/demos/echo/com.example.echo.krl +73 -0
  21. package/demos/echo/try-it.md +5 -0
  22. package/demos/guard_rules/README.md +12 -0
  23. package/demos/guard_rules/com.example.archive.bootstrap.krl +98 -0
  24. package/demos/guard_rules/com.example.archive.krl +213 -0
  25. package/demos/guard_rules/com.example.archive_store.krl +36 -0
  26. package/demos/guard_rules/try-it.md +5 -0
  27. package/demos/json_query/README.md +11 -0
  28. package/demos/json_query/com.example.json_query.bootstrap.krl +84 -0
  29. package/demos/json_query/com.example.json_query.krl +162 -0
  30. package/demos/json_query/try-it.md +5 -0
  31. package/demos/kblog/README.md +14 -0
  32. package/demos/kblog/com.example.kblog.bootstrap.krl +135 -0
  33. package/demos/kblog/com.example.kblog.config.krl +50 -0
  34. package/demos/kblog/com.example.kblog.data.krl +75 -0
  35. package/demos/kblog/com.example.kblog.krl +184 -0
  36. package/demos/kblog/com.example.kblog.posting.krl +109 -0
  37. package/demos/kblog/try-it.md +6 -0
  38. package/demos/layered_rulesets/README.md +13 -0
  39. package/demos/layered_rulesets/com.example.invitations.bootstrap.krl +87 -0
  40. package/demos/layered_rulesets/com.example.invitations.krl +164 -0
  41. package/demos/layered_rulesets/com.example.invitations.short_links.krl +45 -0
  42. package/demos/layered_rulesets/com.example.invitations.welcome.krl +39 -0
  43. package/demos/layered_rulesets/try-it.md +5 -0
  44. package/demos/moving_picos/README.md +15 -0
  45. package/demos/moving_picos/io.picolabs.club_gear_demo.krl +650 -0
  46. package/demos/moving_picos/io.picolabs.ride_coordinator_demo.krl +331 -0
  47. package/demos/score_tracker/README.md +11 -0
  48. package/demos/score_tracker/com.example.score_tracker.bootstrap.krl +107 -0
  49. package/demos/score_tracker/com.example.score_tracker.krl +162 -0
  50. package/demos/score_tracker/try-it.md +5 -0
  51. package/demos/secrets/README.md +12 -0
  52. package/demos/secrets/com.example.hook_service.krl +120 -0
  53. package/demos/secrets/com.example.notifier.bootstrap.krl +130 -0
  54. package/demos/secrets/com.example.notifier.krl +138 -0
  55. package/demos/secrets/try-it.md +5 -0
  56. package/demos/try-it-order.json +1 -0
  57. package/demos/two_picos/README.md +12 -0
  58. package/demos/two_picos/com.example.two_picos.answerer.krl +125 -0
  59. package/demos/two_picos/com.example.two_picos.asker.krl +124 -0
  60. package/demos/two_picos/com.example.two_picos.bootstrap.krl +134 -0
  61. package/demos/two_picos/try-it.md +5 -0
  62. package/demos/xmlui/README.md +17 -0
  63. package/demos/xmlui/com.example.contacts.krl +132 -0
  64. package/demos/xmlui/com.example.fav_color.krl +39 -0
  65. package/demos/xmlui/com.example.guestbook.krl +61 -0
  66. package/demos/xmlui/com.example.hello.krl +19 -0
  67. package/demos/xmlui/com.example.temperature_sensors_view.krl +105 -0
  68. package/demos/xmlui/com.example.thermostat.bootstrap.krl +95 -0
  69. package/demos/xmlui/com.example.thermostat.krl +124 -0
  70. package/demos/xmlui/temperature_sensors.krl +56 -0
  71. package/demos/xmlui/try-it.md +5 -0
  72. package/dist/bundledKrl.js +97 -12
  73. package/dist/cli.js +7 -1
  74. package/dist/engineConfig.js +20 -1
  75. package/dist/identity/portableMove.js +5 -1
  76. package/dist/index.js +45 -12
  77. package/dist/internalAccess.js +110 -0
  78. package/dist/oauth/OAuthService.js +172 -10
  79. package/dist/oauth/acg.js +194 -24
  80. package/dist/oauth/cimd.js +381 -0
  81. package/dist/oauth/discovery.js +175 -0
  82. package/dist/runMcp.js +1 -1
  83. package/dist/server.js +210 -47
  84. package/dist/subtreeWrangler.js +8 -5
  85. package/dist/uiChannelPolicies.js +2 -0
  86. package/krl/io.picolabs.pds.krl +109 -21
  87. package/krl/io.picolabs.pico-engine-ui.krl +13 -7
  88. package/krl/io.picolabs.wrangler.krl +21 -9
  89. package/krl/io.picolabs.xmlui.krl +3 -2
  90. package/mcp/devResources.js +52 -0
  91. package/mcp/devTools.js +40 -9
  92. package/mcp/docs/CLAUDE.md +6 -4
  93. package/mcp/docs/cookbook/README.md +23 -0
  94. package/mcp/docs/cookbook/bootstrap/README.md +23 -0
  95. package/mcp/docs/cookbook/bootstrap/instructions.md +75 -0
  96. package/mcp/docs/cookbook/child_tasks/README.md +20 -0
  97. package/mcp/docs/cookbook/child_tasks/instructions.md +60 -0
  98. package/mcp/docs/cookbook/collection/README.md +21 -0
  99. package/mcp/docs/cookbook/collection/instructions.md +93 -0
  100. package/mcp/docs/cookbook/echo/README.md +19 -0
  101. package/mcp/docs/cookbook/echo/instructions.md +59 -0
  102. package/mcp/docs/cookbook/guard_rules/README.md +22 -0
  103. package/mcp/docs/cookbook/guard_rules/instructions.md +73 -0
  104. package/mcp/docs/cookbook/json_query/README.md +26 -0
  105. package/mcp/docs/cookbook/json_query/instructions.md +64 -0
  106. package/mcp/docs/cookbook/kblog/README.md +60 -0
  107. package/mcp/docs/cookbook/kblog/instructions.md +102 -0
  108. package/mcp/docs/cookbook/layered_rulesets/README.md +24 -0
  109. package/mcp/docs/cookbook/layered_rulesets/instructions.md +87 -0
  110. package/mcp/docs/cookbook/moving_picos/README.md +44 -0
  111. package/mcp/docs/cookbook/moving_picos/instructions.md +150 -0
  112. package/mcp/docs/cookbook/score_tracker/README.md +19 -0
  113. package/mcp/docs/cookbook/score_tracker/instructions.md +73 -0
  114. package/mcp/docs/cookbook/secrets/README.md +25 -0
  115. package/mcp/docs/cookbook/secrets/instructions.md +98 -0
  116. package/mcp/docs/cookbook/two_picos/README.md +20 -0
  117. package/mcp/docs/cookbook/two_picos/instructions.md +88 -0
  118. package/mcp/docs/cookbook/xmlui/README.md +23 -0
  119. package/mcp/docs/cookbook/xmlui/instructions.md +84 -0
  120. package/mcp/docs/developing/README.md +28 -0
  121. package/mcp/docs/developing/accepting-relationship-requests.md +65 -0
  122. package/mcp/docs/developing/arrays-and-maps.md +77 -0
  123. package/mcp/docs/developing/converting-time-formats.md +28 -0
  124. package/mcp/docs/developing/cookies-and-redirects.md +81 -0
  125. package/mcp/docs/developing/decoding-form-data.md +67 -0
  126. package/mcp/docs/developing/engine-log-files.md +34 -0
  127. package/mcp/docs/developing/event-loop.md +77 -0
  128. package/mcp/docs/developing/events-from-email.md +80 -0
  129. package/mcp/docs/developing/initializing-entity-variables.md +83 -0
  130. package/mcp/docs/developing/mcp-ai-tools.md +98 -0
  131. package/mcp/docs/developing/misconceptions.md +467 -0
  132. package/mcp/docs/developing/names-and-scope.md +44 -0
  133. package/mcp/docs/developing/postman.md +159 -0
  134. package/mcp/docs/developing/querying-another-pico.md +47 -0
  135. package/mcp/docs/developing/singleton-picos.md +36 -0
  136. package/mcp/docs/developing/tabular-data.md +67 -0
  137. package/mcp/docs/developing/tips.md +251 -0
  138. package/mcp/docs/developing/webhook-signatures.md +56 -0
  139. package/mcp/docs/developing/workflow.md +106 -0
  140. package/mcp/docs/exp/README.md +46 -0
  141. package/mcp/docs/exp/event.md +110 -0
  142. package/mcp/docs/exp/query.md +94 -0
  143. package/mcp/docs/lessons/README.md +59 -0
  144. package/mcp/docs/lessons/events-and-queries.md +247 -0
  145. package/mcp/docs/lessons/gossip.md +28 -0
  146. package/mcp/docs/lessons/modules-and-apis.md +270 -0
  147. package/mcp/docs/lessons/pico-based-systems.md +470 -0
  148. package/mcp/docs/lessons/pico-state.md +267 -0
  149. package/mcp/docs/lessons/pico-views.md +290 -0
  150. package/mcp/docs/lessons/quickstart.md +157 -0
  151. package/mcp/docs/lessons/relationships.md +530 -0
  152. package/mcp/docs/lessons/scatter-gather.md +362 -0
  153. package/mcp/docs/pico-engine.md +10 -5
  154. package/mcp/docs/pico-overview.md +3 -3
  155. package/mcp/docs/wrangler/README.md +47 -0
  156. package/mcp/docs/wrangler/channels.md +235 -0
  157. package/mcp/docs/wrangler/oauth.md +56 -0
  158. package/mcp/docs/wrangler/pds.md +423 -0
  159. package/mcp/docs/wrangler/portable-subtree.md +44 -0
  160. package/mcp/docs/wrangler/relationships.md +297 -0
  161. package/mcp/docs/wrangler/wrangler.md +253 -0
  162. package/mcp/docs/wrangler/xmlui.md +60 -0
  163. package/mcp/engineClient.js +57 -5
  164. package/mcp/mcpScopes.js +118 -0
  165. package/mcp/meshHttp.js +151 -45
  166. package/mcp/runStdio.js +2 -0
  167. package/mcp/subtreeTools.js +184 -0
  168. package/mcp/tryItTools.js +202 -0
  169. package/package.json +18 -9
  170. package/public/.DS_Store +0 -0
  171. package/public/pico-engine-ui.css +1 -1
  172. package/public/pico-engine-ui.js +26 -25
  173. package/src/bundledKrl.ts +118 -12
  174. package/src/cli.ts +8 -2
  175. package/src/engineConfig.ts +33 -2
  176. package/src/identity/portableMove.ts +6 -1
  177. package/src/index.ts +469 -422
  178. package/src/internalAccess.ts +127 -0
  179. package/src/oauth/OAuthService.ts +243 -11
  180. package/src/oauth/acg.ts +289 -25
  181. package/src/oauth/cimd.ts +508 -0
  182. package/src/oauth/discovery.ts +233 -0
  183. package/src/runMcp.ts +3 -1
  184. package/src/server.ts +266 -51
  185. package/src/subtreeWrangler.ts +17 -5
  186. package/src/uiChannelPolicies.ts +2 -0
@@ -0,0 +1,67 @@
1
+ # Decoding form-encoded data
2
+
3
+ Form-encoded content, such as `q=5&value=%20space%20`, sometimes arrives as a single string: in a webhook body, a stored URL, or a query string you built. A chain of operators turns it into a map.
4
+
5
+ ## Names and values
6
+
7
+ ```krl
8
+ nv_split = function(x) { x.extract(re#([^=]*)=?(.*)#) } // "n=v" -> ["n", "v"]
9
+ frst = function(a) { a.head() }
10
+ dup_1st = function(v) { v[0][1] }
11
+
12
+ decodeContent = function(content) {
13
+ content // "n0=v0&n1=v1&..."
14
+ .split(re#&#) // ["n0=v0", "n1=v1", ...]
15
+ .map(nv_split) // [["n0", "v0"], ["n1", "v1"], ...]
16
+ .collect(frst) // {"n0": [["n0", "v0"]], "n1": [["n1", "v1"]], ...}
17
+ .map(dup_1st) // {"n0": "v0", "n1": "v1", ...}
18
+ }
19
+ ```
20
+
21
+ `decodeContent("q=5&value=%20space%20")` is `{"q": "5", "value": "%20space%20"}`.
22
+
23
+ - `split` makes an array of `name=value` strings.
24
+ - `extract` matches each one against a regular expression and returns its capture groups, the name and the value.
25
+ - `collect` groups the pairs into a map keyed by name. Each value is an array of every pair with that name.
26
+ - The map operator `map` keeps the first value for each name.
27
+
28
+ ## Keep every value of a repeated name
29
+
30
+ When a name can repeat, keep all its values:
31
+
32
+ ```krl
33
+ dup_all = function(v) {
34
+ v.length() == 1 => v[0][1] | v.map(function(w) { w[1] })
35
+ }
36
+ ```
37
+
38
+ Use `.map(dup_all)` in place of `.map(dup_1st)`. `a=1&a=2&b=3` becomes `{"a": ["1", "2"], "b": "3"}`.
39
+
40
+ ## Decode `+` and `%xx`
41
+
42
+ `replace` accepts a function as its second argument. It is called with the match and then each capture group, and returns the replacement:
43
+
44
+ ```krl
45
+ hexDigits = "0123456789abcdef"
46
+
47
+ hex2dec = function(hex) {
48
+ hex like re#^[0-9A-Fa-f]+$#
49
+ => hex.lc().split("").reduce(function(a, h) { a * 16 + hexDigits.split("").index(h) }, 0)
50
+ | null
51
+ }
52
+
53
+ hex2char = function(encoded, hex) {
54
+ val = hex2dec(hex)
55
+ val && val < 128 => val.chr() | encoded
56
+ }
57
+
58
+ decode_val = function(s) {
59
+ s.replace(re#[+]#g, " ").replace(re#%([0-9A-Fa-f]{2})#g, hex2char)
60
+ }
61
+ ```
62
+
63
+ Replace `+` first: early encoders used it for a space, and a real plus sign arrives as `%2B`. Then use `function(v) { decode_val(v[0][1]) }` as the last step of the chain. `value=%20space%20&plus=a%2Bb&pct=100%25` becomes `{"value": " space ", "plus": "a+b", "pct": "100%"}`. This handles ASCII characters. Anything above 127 is left encoded.
64
+
65
+ Events and queries that arrive over HTTP are already decoded: the engine gives you their attributes as a map. This is for strings you have in hand.
66
+
67
+ *From the Pico Labs KRL Cookbook page "Decoding WWW-Form Encoded Content or Query Parameters".*
@@ -0,0 +1,34 @@
1
+ # Reading the engine's log files
2
+
3
+ The **Logging** tab shows recent events and queries for a pico, from the engine's memory. To look further back, or across every pico, read the log files.
4
+
5
+ ## Where they are
6
+
7
+ The engine writes one JSON object per line to `pico-engine.log` in its home directory (`PICO_ENGINE_HOME`, `~/.pico-engine` by default). When the file reaches 100 MB it rotates: the older entries move to `pico-engine.log.1`, `pico-engine.log.2`, and so on, and the engine keeps up to twelve files. `PICO_ENGINE_LOG_FILE` writes somewhere else instead (`stdout` to write to standard output). See [the operator guide](/pico-engine) for the settings.
8
+
9
+ Each line has `level`, `time`, and `msg`, and lines about a pico's work have `picoId` and `txnId`. A transaction is one event or query and everything it caused.
10
+
11
+ ```json
12
+ {"level":50,"time":"2026-11-13T18:46:16.317Z","picoId":"cmwfbv2y1001e4jysd0cn9w05","txnId":"cmwfbvcvx00244jysd16w7grz","txnKind":"query","error":"This is a family channel and only the owner can use it.","msg":"..."}
13
+ ```
14
+
15
+ ## One pico's history
16
+
17
+ Find the pico's id on its **About** tab, then:
18
+
19
+ ```sh
20
+ cd ~/.pico-engine
21
+ grep -h '"picoId":"<pico id>"' pico-engine.log* | jq -s -c 'sort_by(.time)[]' > my_pico.log
22
+ ```
23
+
24
+ `grep` collects the lines from every file, and [`jq`](https://jqlang.org/) sorts them by time, since rotated files aren't in order relative to each other. To follow one event through everything it caused, filter on its `txnId` instead.
25
+
26
+ ## What to look for
27
+
28
+ - `"msg":"txnQueued"` lines show each event or query as it arrived, with its attributes.
29
+ - `"error"` fields show what failed: a channel policy refusal, a KRL runtime error, a family channel used from outside.
30
+ - `klog` output from your own rules is in the log, with the message you gave it.
31
+
32
+ The logs hold every event's attributes. Anything secret that arrives in an event is in them. See the [Configuration and secrets](/cookbook/secrets/) demo.
33
+
34
+ *From the Pico Labs KRL Cookbook page "Examining pico-engine log files". The log format and rotation have changed since that page was written.*
@@ -0,0 +1,77 @@
1
+ # Event Loop Introduction
2
+
3
+ Each pico presents an event loop that handles the events sent to it, according to the rulesets installed in it. The event is the input that makes the cycle happen. When the event has been handled, the pico waits for the next one.
4
+
5
+ <img src="/developing/_media/1189951-image2021-2-22_15-2-38.png" alt="Pico event evaluation cycle: wait, decode event, schedule rules, eval rules, assemble response" width="50%">
6
+
7
+ The five phases, in order: **Wait**, **Decode**, **Schedule Rules**, **Rule Evaluation**, **Assembling the Response**. Then the pico waits again.
8
+
9
+ ## Wait
10
+
11
+ A pico spends nearly all its time waiting. An idle pico does no work.
12
+
13
+ Events the pico receives are added to its event queue and handled in the order received. The pico leaves the wait phase when the queue has an event to process.
14
+
15
+ **Picos are single-threaded.** A pico never processes two events at the same time, so rules in one pico can't race each other over its entity variables. Other events that arrive meanwhile queue up.
16
+
17
+ ## Decode
18
+
19
+ The decode phase unpacks the event from whatever carried it and puts it in a common form, the *request* that the rest of the cycle uses whenever it needs information about the event: its domain, type, attributes, and event id.
20
+
21
+ Most events arrive over HTTP, through the [Sky event API](/exp/event) (`/sky/event/<eci>/<eid>/<domain>/<type>`). The channel in the URL picks the pico and its policy decides whether this domain and type is allowed in. Events sent from another pico with `event:send` arrive the same way, and events raised by the pico itself skip the transport altogether. Other transports could be supported by adding a decoder.
22
+
23
+ ## Schedule Rules
24
+
25
+ Building the schedule determines what happens for the rest of the cycle.
26
+
27
+ The engine keeps a *salience graph* for each pico. For any event domain and type, it tells which rules are *salient*: which have an event expression that mentions that domain and type. The incoming event has one domain and one type, and the engine looks up the rules that are listening for that pair and puts them on the **schedule**.
28
+
29
+ The graph is computed from the rulesets installed in the pico, so it's recalculated whenever the pico's rulesets change. It acts as an event bus: when you install a ruleset, its rules are subscribed to the events they select on, with no other wiring.
30
+
31
+ Order matters in some places and not in others:
32
+
33
+ - **Within a ruleset**, rules appear in the schedule in the order they are written.
34
+ - **Across rulesets**, there is no defined order. Don't count on one ruleset's rules running before or after another's. If you need an order, make it explicit with events (see below).
35
+
36
+ "Salient" doesn't mean "will run". A rule on the schedule has only shown that it listens for this domain and type.
37
+
38
+ ## Rule Evaluation
39
+
40
+ The engine goes down the schedule one rule at a time. For each rule it evaluates the event expression to see whether the rule is *selected*, and if so runs it: the prelude, the action when its condition is true, and then the postlude. A rule can be on the schedule and still not be selected, such as when a compound event expression is waiting for another event, or a `where` clause is false.
41
+
42
+ Most of what a rule does doesn't affect the loop. Two things do:
43
+
44
+ - **`raise` appends to the schedule.** A `raise` in a postlude doesn't call anything. The engine looks up the rules salient for the raised event and **appends** them to the end of the schedule, and the current rule's evaluation continues from where it left off. Everything scheduled by the original event runs before anything scheduled by a raised event. This is why `raise` is not a function call, and why a rule that raises an event and then expects the effect right away is surprised. See [KRL misconceptions](/developing/misconceptions#order-of-rule-evaluation).
45
+ - **`last`** in a postlude stops the remaining rules of that ruleset on the schedule.
46
+
47
+ Rules that raise events are still within the same pico and the same cycle. The whole cascade runs, and the schedule empties, before the cycle ends.
48
+
49
+ Two other kinds of effects are outside the schedule:
50
+
51
+ - **HTTP calls.** A synchronous call to an external API from the [http library](/krl/libraries/http) makes the rule wait until the resource answers, and the pico handles nothing else meanwhile, since it's single-threaded.
52
+ - **Sending an event to another pico.** `event:send` is **asynchronous**. It starts an independent cycle in the receiving pico and doesn't change the schedule you're running. If both picos are on the same engine they run concurrently, though not necessarily in parallel. You can't assume anything about their relative order unless you make one, usually by having the receiver send an event back when it's done. The [Scatter-Gather](/lessons/scatter-gather) lesson does exactly this, with a correlation id so the gatherer can tell which reply is which.
53
+
54
+ If a pico sends an event to its *own* channel, that event goes to the back of its queue and is handled in a later cycle, since the pico is busy.
55
+
56
+ ## Assembling the Response
57
+
58
+ When the schedule is empty, the engine assembles the response from the output of all the rules that fired: the directives (`send_directive`), the outcome of each rule, and the events raised during the cycle. Over HTTP this is the JSON body described on the [Event API](/exp/event#response) page.
59
+
60
+ An event having a response is unusual, and mostly a historical convenience. For an event sent synchronously over HTTP the response confirms that it arrived and was processed, and it can carry useful results. Events sent asynchronously, including `event:send` from a rule, never have a response the sender can use. Responses are optional and depend on which rules ran.
61
+
62
+ ## Waiting again
63
+
64
+ Once the response has gone, the pico takes the next event in its queue, or waits if the queue is empty.
65
+
66
+ Queries are separate. They call a shared function and return its value, and they don't run rules or change the pico (see [Query API](/exp/query)).
67
+
68
+ ## See also
69
+
70
+ - [Events and Queries](/lessons/events-and-queries): events and queries over HTTP, with the Logging tab showing each cycle
71
+ - [Scatter-Gather](/lessons/scatter-gather): ordering concurrent picos explicitly
72
+ - [KRL misconceptions and common errors](/developing/misconceptions)
73
+ - [Event expressions](/krl/event-expressions/) and [raising explicit events](/krl/rulesets/rules/postlude/raising-explicit-events-in-the-postlude) in the KRL manual
74
+
75
+ ---
76
+
77
+ <small>Ported from the [Pico Labs wiki](https://picolabs.atlassian.net/wiki/spaces/docs/pages/1189951) (by Phil Windley; last edited there 2021-02-22), and updated for this engine.</small>
@@ -0,0 +1,80 @@
1
+ # Events from email
2
+
3
+ Any service that can call a webhook can raise events on a pico. Email is a good example: services such as [CloudMailin](https://www.cloudmailin.com/) give you an address and POST each message that arrives to a URL you choose. Point that URL at a pico:
4
+
5
+ ```
6
+ https://<your engine>/sky/event/<eci>/mail/mail/received
7
+ ```
8
+
9
+ The engine has to be reachable from the internet. For an engine on your own machine, a tunnel such as [ngrok](https://ngrok.com/) gives it a public address. Use a channel made for this purpose, whose policy allows only `mail:received`, so the webhook URL can't do anything else.
10
+
11
+ ## Parse the message
12
+
13
+ The service's POST body becomes the event's attributes. With CloudMailin's JSON format, the headers and the plain-text body are in `headers` and `plain`:
14
+
15
+ ```krl
16
+ rule mail_incoming {
17
+ select when mail received
18
+ pre {
19
+ headers = event:attr("headers").defaultsTo({})
20
+ }
21
+ always {
22
+ raise mail event "parsed" attributes {
23
+ "date": headers{"Date"},
24
+ "to": headers{"To"},
25
+ "from": headers{"From"},
26
+ "subject": headers{"Subject"},
27
+ "text": event:attr("plain")
28
+ }
29
+ }
30
+ }
31
+ ```
32
+
33
+ ## Route it to another pico
34
+
35
+ One mail pico can serve many. Put the target pico's channel id in the address, as in `me+<eci>@cloudmailin.net`, and forward on it:
36
+
37
+ ```krl
38
+ rule mail_router {
39
+ select when mail parsed
40
+ to re#[+]([^@]*)@#
41
+ setting(eci)
42
+ event:send({"eci": eci, "domain": "mail", "type": "events", "attrs": event:attrs})
43
+ }
44
+ ```
45
+
46
+ The person writing the email needs that address, but not where the target pico lives.
47
+
48
+ ## Turn lines into events
49
+
50
+ The target pico can treat each line of the body as an event to raise. Here, a line such as `aurora/on` raises `aurora:on`, and every other line is ignored:
51
+
52
+ ```krl
53
+ rule mail_events {
54
+ select when mail events
55
+ foreach event:attr("text").defaultsTo("").split(re#\r?\n#) setting(request)
56
+ pre {
57
+ parts = request.split(re#/#)
58
+ wanted = parts.length() == 2 && parts[0] == "aurora"
59
+ }
60
+ if wanted then noop()
61
+ fired {
62
+ raise aurora event parts[1]
63
+ }
64
+ }
65
+ ```
66
+
67
+ A body of
68
+
69
+ ```
70
+ Turn on the lights, then show the second theme after this one.
71
+ aurora/on
72
+ aurora/next
73
+ aurora/next
74
+ ```
75
+
76
+ raises `aurora:on` and `aurora:next` twice, which the pico's existing rulesets handle. The new ruleset doesn't change them.
77
+
78
+ Parsing the body is the fragile part. Email clients add things you don't expect, such as invisible characters. Test with messages from the clients your senders use.
79
+
80
+ *From the Pico Labs KRL Cookbook page "Triggering Events from Email Messages".*
@@ -0,0 +1,83 @@
1
+ # Initializing entity variables
2
+
3
+ Each ruleset installed in a pico gives the pico its own entity variables, specific to that pico and that ruleset. Until a rule's postlude first assigns one, its value is `null`. There are three ways to deal with that.
4
+
5
+ ## Use `defaultsTo` wherever you read it
6
+
7
+ `defaultsTo` supplies a value when the variable is `null`. Suppose `ent:owners` will be a map but might not exist yet:
8
+
9
+ ```krl
10
+ nameExists = function(ownername) {
11
+ ent:owners.defaultsTo({}) >< ownername
12
+ }
13
+ ```
14
+
15
+ The first time the map is stored, start from the same default:
16
+
17
+ ```krl
18
+ rule owner_token {
19
+ select when owner token_created
20
+ pre {
21
+ name = event:attr("name")
22
+ new_owner = event:attr("owner")
23
+ }
24
+ fired {
25
+ ent:owners := ent:owners.defaultsTo({}).put(name, new_owner)
26
+ }
27
+ }
28
+ ```
29
+
30
+ With this technique, every use of `ent:owners` in the ruleset needs `defaultsTo`. A shared function that returns `ent:owners.defaultsTo({})` keeps that in one place.
31
+
32
+ ## Initialize it in a guard rule
33
+
34
+ Put a rule before the others that select the same event, and have it create the variable when it is missing:
35
+
36
+ ```krl
37
+ rule guard_owners_map {
38
+ select when owner token_created
39
+ if ent:owners.isnull() then noop()
40
+ fired {
41
+ ent:owners := {}
42
+ }
43
+ }
44
+ ```
45
+
46
+ Rules in one ruleset that select the same event run in the order they are written, so this one runs first. The rules after it can then use a path assignment, which is also faster for a large map:
47
+
48
+ ```krl
49
+ rule owner_token {
50
+ select when owner token_created
51
+ pre {
52
+ name = event:attr("name")
53
+ new_owner = event:attr("owner")
54
+ }
55
+ fired {
56
+ ent:owners{name} := new_owner
57
+ }
58
+ }
59
+ ```
60
+
61
+ Functions still need `defaultsTo`, in case a query arrives before any event does.
62
+
63
+ ## Initialize it when the ruleset is installed
64
+
65
+ A rule that selects the ruleset's own `wrangler:ruleset_installed` runs before anything else can use the ruleset:
66
+
67
+ ```krl
68
+ rule initialization {
69
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
70
+ if ent:owners.isnull() then noop()
71
+ fired {
72
+ ent:owners := {}
73
+ }
74
+ }
75
+ ```
76
+
77
+ The `where` clause matters. Many rulesets are installed in a pico over its life, and without it this rule would run every time. Checking `isnull()` first is good practice too.
78
+
79
+ Installing again from the same URL, or flushing, does not raise `ruleset_installed` again. A rule like this runs once per install.
80
+
81
+ See also: [Persistent variables](/krl/persistent-variables/) in the KRL manual, and the [Guard rules](/cookbook/guard_rules/) demo.
82
+
83
+ *From the Pico Labs KRL Cookbook page "Initializing entity variables".*
@@ -0,0 +1,98 @@
1
+ # AI tools over MCP
2
+
3
+ An MCP client such as Claude can call a pico the same way it calls any remote MCP server: add a URL, sign in with a passkey, approve, and use the tools. The engine also has a separate local MCP server for coding agents on the same machine. That one is `pico-engine mcp --stdio` and does not use this sign-in. This page is the remote connection.
4
+
5
+ ## Which URL
6
+
7
+ | You want | URL | Tools |
8
+ |----------|-----|--------|
9
+ | One channel | `https://<engine>/mcp/<eci>` | That channel's events and queries, one tool each |
10
+ | The mesh under a channel | `https://<engine>/mcp/mesh/<eci>` | `pico_tree`, `pico_channels`, `query`, `raise_event` |
11
+
12
+ No trailing slash. An ECI is a channel id from the Channels tab.
13
+
14
+ `mesh:read` covers schemas, lists, and queries. `mesh:act` covers events. `mesh:admin` is reserved and unlocks nothing. A sign-in that does not name a narrower scope receives both `mesh:read` and `mesh:act`.
15
+
16
+ A channel is not exposed until you allow it. On the Channels tab, check the channel surface for `/mcp/<eci>`, or the mesh surface for a channel that should appear in `/mcp/mesh/…`. The channel you name in the mesh URL does not itself need the mesh checkbox. A missing or empty policy denies both surfaces. A pico ceiling from an older engine does not block this. A ceiling that has its own `mcpPolicy` does.
17
+
18
+ On a channel endpoint, that channel's event and query policies decide which calls succeed. The tools are the events and queries those policies allow. A mesh endpoint is not bound to the policies of the channel in the URL. `pico_tree` and `pico_channels` list the subtree. `query` and `raise_event` name some other channel, and that channel's event and query policies are what allow or refuse the call. `pico_channels` includes a channel only when its MCP policy allows the mesh surface.
19
+
20
+ ## The root has to allow OAuth
21
+
22
+ Install `io.picolabs.oauth` on the **root** pico before anyone signs in. The Engine KRL Directory lists it only on the root. On the Rulesets tab the URL is `https://<engine>/krl/io.picolabs.oauth.krl`.
23
+
24
+ That ruleset is the switch for issuing sign-in tokens. A connector for one channel and a connector for the whole mesh both require it. The channel URL still limits the token to that channel. Installing the ruleset also makes external `/sky/*` calls on the mesh require a bearer token. Channels tagged `mesh-oauth-exempt`, or `didcomm` and `ingress`, stay open. See [OAuth](/wrangler/oauth).
25
+
26
+ A channel tagged `oauth-webhook` can obtain a client-credentials token for its own MCP URL without this ruleset. That is a machine credential, not the passkey sign-in below.
27
+
28
+ ## Claude cannot use localhost
29
+
30
+ Claude connects from Anthropic's network, including from Claude Desktop. The connector URL must be HTTPS on port 443. `http://localhost:3000` and a URL with another port are refused.
31
+
32
+ Keep the engine on port 3000 and put a tunnel in front of it. A Cloudflare quick tunnel does not need an account:
33
+
34
+ ```sh
35
+ brew install cloudflared
36
+ cloudflared tunnel --url http://localhost:3000
37
+ ```
38
+
39
+ The public URL is in the box near the top of the output, `https://….trycloudflare.com`. A line about a missing `config.yml` is normal. Leave that process running. The hostname changes if you stop it and start it again. Anyone with the URL can reach the engine, so stop the tunnel when you are done.
40
+
41
+ Quick tunnels do not carry server-sent events. If sign-in succeeds and the tools then fail to stay connected, use `ngrok http 3000` instead. A named Cloudflare tunnel, with a hostname you choose, needs a free Cloudflare account and a domain on Cloudflare.
42
+
43
+ ## Set the host before you create the account
44
+
45
+ A passkey works only for the host it was created on. A passkey for `localhost` will not sign in on the tunnel host, and a passkey for one quick-tunnel hostname will not sign in on the next one. Channels do not store the host. The account that owns them does. Create the passkey, then the channel, on the host Claude will use.
46
+
47
+ 1. Start the tunnel and copy the hostname.
48
+ 2. Point the engine at that host and restart it. In the config file (`~/.config/pico-engine/config.json`, or the file in `PICO_ENGINE_CONFIG`):
49
+
50
+ ```json
51
+ {
52
+ "baseUrl": "https://example.trycloudflare.com",
53
+ "allowSelfSignup": true,
54
+ "webauthn": {
55
+ "rpId": "example.trycloudflare.com",
56
+ "origin": "https://example.trycloudflare.com",
57
+ "rpName": "Pico Engine"
58
+ }
59
+ }
60
+ ```
61
+
62
+ `baseUrl` and `origin` have no trailing slash and no port. `rpId` is the hostname only. `allowSelfSignup` can go back to `false` after the account exists. The engine reads this file at startup.
63
+ 3. Open the tunnel URL in a browser and register a passkey.
64
+ 4. Install `io.picolabs.oauth` on that root.
65
+ 5. Open the Channels tab, allow the channel MCP surface on the channel the agent should use, and copy its ECI.
66
+
67
+ The connector URL is then `https://example.trycloudflare.com/mcp/<eci>`.
68
+
69
+ ## Add the connector in Claude
70
+
71
+ On a Pro or Max plan: **Customize** → **Connectors** → **+ Add** → **Add custom connector**.
72
+
73
+ On a Team or Enterprise plan an owner adds it under **Organization settings** → **Connectors** → **Add** → **Custom** → **Web**. Each person then connects it from **Customize** → **Connectors**.
74
+
75
+ - Name it whatever you like.
76
+ - Remote MCP server URL: the channel or mesh URL from above, exactly.
77
+ - Authentication: **Sign in now**.
78
+ - OAuth client: **Use Claude's published identity**. Leave the client id and secret empty.
79
+
80
+ **Register automatically** is dynamic client registration. This engine does not offer it. **Use your own OAuth client** is an `app_…` client you create on the engine first. The "Detected" label means Claude found an OAuth server, not that a client id is required.
81
+
82
+ If Claude says automatic client registration is not supported, or the connector page says the connection stopped working and never opens the passkey page, remove the connector and add it again with **Use Claude's published identity**. **Reconnect** repeats the registration attempt Claude already saved.
83
+
84
+ The passkey page is the tunnel host, not `localhost`. Sign in, then approve. The approval screen names Claude, its host, the mesh, and the scopes. After that, turn the connector on from the **+** menu in a chat. Ask it to run a query (`mesh:read`) or raise an event (`mesh:act`).
85
+
86
+ A public client's access token lasts one hour. Each refresh returns a new refresh token. Sending the previous refresh token again revokes that grant.
87
+
88
+ ## What another MCP client needs
89
+
90
+ A client that implements the MCP authorization spec can use the same URLs. A request with no bearer token gets `401` and a `WWW-Authenticate` header pointing at the protected-resource document.
91
+
92
+ | Document | URL |
93
+ |----------|-----|
94
+ | Protected resource, one channel | `/.well-known/oauth-protected-resource/mcp/<eci>` |
95
+ | Protected resource, mesh | `/.well-known/oauth-protected-resource/mcp/mesh/<eci>` |
96
+ | Authorization server | `/.well-known/oauth-authorization-server` |
97
+
98
+ The same authorization-server document is also served with the MCP path inserted, and at `/.well-known/openid-configuration`, because some clients look there first. PKCE is S256 only. A `client_id` that is an `https` URL is fetched as a Client ID Metadata Document. The token endpoint accepts a public client (`none`) and a confidential client that sends its secret in the body (`client_secret_post`). The token's `resource` is the MCP URL it was issued for. A token for one channel is rejected on another channel and on `/sky/*`.