fmind 2.0.3__tar.gz → 2.0.5__tar.gz

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.
fmind-2.0.5/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Médéric Hurier (Fmind)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,11 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fmind
3
- Version: 2.0.3
3
+ Version: 2.0.5
4
4
  Summary: Read Médéric Hurier's (Fmind) portfolio from the terminal.
5
5
  Keywords: portfolio,cli,fmind,resume,articles
6
6
  Author: Médéric Hurier
7
7
  Author-email: Médéric Hurier <contact@fmind.dev>
8
8
  License-Expression: MIT
9
+ License-File: LICENSE
9
10
  Classifier: Environment :: Console
10
11
  Classifier: Intended Audience :: Developers
11
12
  Classifier: Programming Language :: Python :: 3 :: Only
@@ -32,22 +33,22 @@ uvx fmind whoami
32
33
 
33
34
  ## Commands
34
35
 
35
- | Command | Shows |
36
- | ------------------------------------------- | ------------------------------------------------- |
37
- | `fmind` | The `whoami` card and a pointer to `--help` |
38
- | `fmind whoami` | Name, featured experience, availability, contact |
39
- | `fmind about` | The biography |
40
- | `fmind skills` | Core expertise, as published on the site |
41
- | `fmind experiences` | Engagements in website order |
42
- | `fmind community` | Ambassador and advisory roles |
43
- | `fmind certifications` | Certifications, the PhD, specializations |
44
- | `fmind papers` | The doctorate and the peer-reviewed publications |
45
- | `fmind projects [--limit 6]` | Open-source repositories and video series |
46
- | `fmind sites` | Interactive tools published alongside the writing |
47
- | `fmind articles [--limit 6]` | The most recent writing |
48
- | `fmind search [query] [--tag] [--limit 10]` | Articles matching every term, newest first |
49
- | `fmind read <slug> [--raw]` | One article, rendered in the terminal |
50
- | `fmind hire` | What can be booked right now |
36
+ | Command | Shows |
37
+ | ---------------------------------------------- | ------------------------------------------------- |
38
+ | `fmind` | The `whoami` card and a pointer to `--help` |
39
+ | `fmind whoami` | Name, featured experience, availability, contact |
40
+ | `fmind about` | The biography |
41
+ | `fmind skills` | Core expertise, as published on the site |
42
+ | `fmind experiences` | Engagements in website order |
43
+ | `fmind community` | Ambassador and advisory roles |
44
+ | `fmind certifications` | Certifications, the PhD, specializations |
45
+ | `fmind papers` | The doctorate and the peer-reviewed publications |
46
+ | `fmind projects [--limit 6]` | Open-source repositories and video series |
47
+ | `fmind sites` | Interactive tools published alongside the writing |
48
+ | `fmind articles [--limit 6]` | The most recent writing |
49
+ | `fmind search [query...] [--tag] [--limit 10]` | Articles matching every term, newest first |
50
+ | `fmind read <slug> [--raw]` | One article, rendered in the terminal |
51
+ | `fmind hire` | What can be booked right now |
51
52
 
52
53
  The commands group sections of the website's profile API. Their names stay stable when the website's navigation or visual design changes.
53
54
 
@@ -59,14 +60,14 @@ Output uses your terminal's default text colour and blue accent. Community roles
59
60
 
60
61
  ### Reading
61
62
 
62
- `fmind search` matches titles, summaries, tags and slugs; terms are ANDed, so each extra word narrows the result. `--tag` restricts to one of the site's own tags, case-insensitively; an unknown tag fails and lists the published ones.
63
+ `fmind search` matches titles, summaries, tags and slugs; terms are ANDed, so each extra word narrows the result, with or without quotes. `--tag` restricts to one of the site's own tags, case-insensitively; an unknown tag fails and lists the published ones.
63
64
 
64
65
  ```bash
65
- fmind search "agent security"
66
+ fmind search agent security
66
67
  fmind search --tag MLOps --limit 3
67
68
  ```
68
69
 
69
- `fmind read` takes a slug, or enough of one to be unambiguous, and prints the article. In an interactive terminal it pages through `$PAGER` (default `less`, with `LESS=FRX` unless you set `LESS`), so short articles print directly; `PAGER=cat` disables paging. If the selected pager cannot start or exits unsuccessfully, the command reports an error; retry with `PAGER=cat`. Use `--raw` for the Markdown source.
70
+ `fmind read` takes a slug, or enough of one to be unambiguous, and prints the article. In an interactive terminal whose `TERM` your system's terminfo database knows (not `dumb`), it pages through `$PAGER` (default `less`, with `LESS=FRX` unless you set `LESS`), so short articles print directly; `PAGER=cat` disables paging. A missing or unparsable `PAGER` is skipped and the article prints directly; if the pager fails to launch or exits unsuccessfully, the command reports an error; retry with `PAGER=cat`. Use `--raw` for the Markdown source.
70
71
 
71
72
  ```bash
72
73
  slug="$(fmind articles --limit 1 --json | jq -r '.[0].slug')"
@@ -128,7 +129,7 @@ For a host that accepts JSON configuration:
128
129
  }
129
130
  ```
130
131
 
131
- `fmind mcp` connects to `https://www.fmind.dev/mcp` using Streamable HTTP and forwards the website's tools, resources, and prompts over stdio. The website owns their names, schemas, and content. Set `FMIND_PROFILE_URL` in the host's environment to use `/mcp` on another website origin. No local data or response cache is used. The website answers MCP POST requests with JSON; GET/HEAD return `405` with `Allow: POST` because notification streams are not offered. Use `/health` for uptime probes. Requests have a 15-second deadline and remote HTTP responses are limited to 8 MiB.
132
+ `fmind mcp` connects to `https://www.fmind.dev/mcp` using Streamable HTTP and forwards the website's tools, resources, and prompts over stdio. The website owns their names, schemas, and content. Set `FMIND_PROFILE_URL` in the host's environment to use `/mcp` on another website origin. No local data or response cache is used. The website answers MCP POST requests with JSON; GET/HEAD return `405` with `Allow: POST` because notification streams are not offered. Use `/health` for uptime probes. Requests have a 15-second deadline and remote HTTP responses are limited to 8 MiB. A request that exceeds these bounds or loses its connection fails on its own, and the bridge keeps serving.
132
133
 
133
134
  Stdout carries only MCP messages; startup errors go to stderr. Portfolio output flags such as `--json` do not apply to `mcp`. The bridge forwards read-only request/response operations; subscriptions and server-initiated sampling or elicitation are not advertised.
134
135
 
@@ -140,15 +141,16 @@ From this checkout, run `uv run --extra mcp fmind mcp`. The optional extra uses
140
141
  mise install # install the pinned toolchain
141
142
  mise run install # sync the locked environment and install hooks
142
143
  mise run format # ruff imports and format, dprint
143
- mise run check # ruff, ty, actionlint, zizmor, gitleaks, dependency audit
144
+ mise run check # lockfile, ruff, ty, dprint, jactionlint, betterleaks, dependency audit
144
145
  mise run test # offline pytest with branch coverage
145
146
  mise run smoke # exercise every command against the live site
147
+ mise run build # build the wheel and source distribution
146
148
  mise run all # format, check, test, build — the gate CI runs
147
149
  ```
148
150
 
149
- The pre-commit hook runs checks without changing or staging files; run `mise run format` before committing. The pre-push hook runs the offline tests. CI runs the full gate on the pinned Python, tests Python 3.11–3.13 for compatibility, and tests the declared dependency floors with `--resolution lowest-direct` on Python 3.11.
151
+ The pre-commit hook formats staged files and runs the offline checks (`mise run check:local`). The pre-push hook runs the dependency audit (`mise run check:network`) and the offline tests. CI runs the full gate on the pinned Python, tests Python 3.11–3.15 for compatibility, and tests the declared dependency floors with `--resolution lowest-direct` on Python 3.11.
150
152
 
151
- A release tag must match the version in `pyproject.toml` (for example, `v0.1.0`). CD runs the same full gate for that tag and checks the live commands before publishing through PyPI Trusted Publishing. The live smoke check is a release check, not a pull-request gate.
153
+ A release tag must match the version in `pyproject.toml` (for example, `v0.1.0`). CD reruns every CI job for that tag (the gate, the Python versions, and the dependency floors) and checks the live commands before publishing through PyPI Trusted Publishing. The live smoke check is a release check, not a pull-request gate.
152
154
 
153
155
  ## License
154
156
 
@@ -8,22 +8,22 @@ uvx fmind whoami
8
8
 
9
9
  ## Commands
10
10
 
11
- | Command | Shows |
12
- | ------------------------------------------- | ------------------------------------------------- |
13
- | `fmind` | The `whoami` card and a pointer to `--help` |
14
- | `fmind whoami` | Name, featured experience, availability, contact |
15
- | `fmind about` | The biography |
16
- | `fmind skills` | Core expertise, as published on the site |
17
- | `fmind experiences` | Engagements in website order |
18
- | `fmind community` | Ambassador and advisory roles |
19
- | `fmind certifications` | Certifications, the PhD, specializations |
20
- | `fmind papers` | The doctorate and the peer-reviewed publications |
21
- | `fmind projects [--limit 6]` | Open-source repositories and video series |
22
- | `fmind sites` | Interactive tools published alongside the writing |
23
- | `fmind articles [--limit 6]` | The most recent writing |
24
- | `fmind search [query] [--tag] [--limit 10]` | Articles matching every term, newest first |
25
- | `fmind read <slug> [--raw]` | One article, rendered in the terminal |
26
- | `fmind hire` | What can be booked right now |
11
+ | Command | Shows |
12
+ | ---------------------------------------------- | ------------------------------------------------- |
13
+ | `fmind` | The `whoami` card and a pointer to `--help` |
14
+ | `fmind whoami` | Name, featured experience, availability, contact |
15
+ | `fmind about` | The biography |
16
+ | `fmind skills` | Core expertise, as published on the site |
17
+ | `fmind experiences` | Engagements in website order |
18
+ | `fmind community` | Ambassador and advisory roles |
19
+ | `fmind certifications` | Certifications, the PhD, specializations |
20
+ | `fmind papers` | The doctorate and the peer-reviewed publications |
21
+ | `fmind projects [--limit 6]` | Open-source repositories and video series |
22
+ | `fmind sites` | Interactive tools published alongside the writing |
23
+ | `fmind articles [--limit 6]` | The most recent writing |
24
+ | `fmind search [query...] [--tag] [--limit 10]` | Articles matching every term, newest first |
25
+ | `fmind read <slug> [--raw]` | One article, rendered in the terminal |
26
+ | `fmind hire` | What can be booked right now |
27
27
 
28
28
  The commands group sections of the website's profile API. Their names stay stable when the website's navigation or visual design changes.
29
29
 
@@ -35,14 +35,14 @@ Output uses your terminal's default text colour and blue accent. Community roles
35
35
 
36
36
  ### Reading
37
37
 
38
- `fmind search` matches titles, summaries, tags and slugs; terms are ANDed, so each extra word narrows the result. `--tag` restricts to one of the site's own tags, case-insensitively; an unknown tag fails and lists the published ones.
38
+ `fmind search` matches titles, summaries, tags and slugs; terms are ANDed, so each extra word narrows the result, with or without quotes. `--tag` restricts to one of the site's own tags, case-insensitively; an unknown tag fails and lists the published ones.
39
39
 
40
40
  ```bash
41
- fmind search "agent security"
41
+ fmind search agent security
42
42
  fmind search --tag MLOps --limit 3
43
43
  ```
44
44
 
45
- `fmind read` takes a slug, or enough of one to be unambiguous, and prints the article. In an interactive terminal it pages through `$PAGER` (default `less`, with `LESS=FRX` unless you set `LESS`), so short articles print directly; `PAGER=cat` disables paging. If the selected pager cannot start or exits unsuccessfully, the command reports an error; retry with `PAGER=cat`. Use `--raw` for the Markdown source.
45
+ `fmind read` takes a slug, or enough of one to be unambiguous, and prints the article. In an interactive terminal whose `TERM` your system's terminfo database knows (not `dumb`), it pages through `$PAGER` (default `less`, with `LESS=FRX` unless you set `LESS`), so short articles print directly; `PAGER=cat` disables paging. A missing or unparsable `PAGER` is skipped and the article prints directly; if the pager fails to launch or exits unsuccessfully, the command reports an error; retry with `PAGER=cat`. Use `--raw` for the Markdown source.
46
46
 
47
47
  ```bash
48
48
  slug="$(fmind articles --limit 1 --json | jq -r '.[0].slug')"
@@ -104,7 +104,7 @@ For a host that accepts JSON configuration:
104
104
  }
105
105
  ```
106
106
 
107
- `fmind mcp` connects to `https://www.fmind.dev/mcp` using Streamable HTTP and forwards the website's tools, resources, and prompts over stdio. The website owns their names, schemas, and content. Set `FMIND_PROFILE_URL` in the host's environment to use `/mcp` on another website origin. No local data or response cache is used. The website answers MCP POST requests with JSON; GET/HEAD return `405` with `Allow: POST` because notification streams are not offered. Use `/health` for uptime probes. Requests have a 15-second deadline and remote HTTP responses are limited to 8 MiB.
107
+ `fmind mcp` connects to `https://www.fmind.dev/mcp` using Streamable HTTP and forwards the website's tools, resources, and prompts over stdio. The website owns their names, schemas, and content. Set `FMIND_PROFILE_URL` in the host's environment to use `/mcp` on another website origin. No local data or response cache is used. The website answers MCP POST requests with JSON; GET/HEAD return `405` with `Allow: POST` because notification streams are not offered. Use `/health` for uptime probes. Requests have a 15-second deadline and remote HTTP responses are limited to 8 MiB. A request that exceeds these bounds or loses its connection fails on its own, and the bridge keeps serving.
108
108
 
109
109
  Stdout carries only MCP messages; startup errors go to stderr. Portfolio output flags such as `--json` do not apply to `mcp`. The bridge forwards read-only request/response operations; subscriptions and server-initiated sampling or elicitation are not advertised.
110
110
 
@@ -116,15 +116,16 @@ From this checkout, run `uv run --extra mcp fmind mcp`. The optional extra uses
116
116
  mise install # install the pinned toolchain
117
117
  mise run install # sync the locked environment and install hooks
118
118
  mise run format # ruff imports and format, dprint
119
- mise run check # ruff, ty, actionlint, zizmor, gitleaks, dependency audit
119
+ mise run check # lockfile, ruff, ty, dprint, jactionlint, betterleaks, dependency audit
120
120
  mise run test # offline pytest with branch coverage
121
121
  mise run smoke # exercise every command against the live site
122
+ mise run build # build the wheel and source distribution
122
123
  mise run all # format, check, test, build — the gate CI runs
123
124
  ```
124
125
 
125
- The pre-commit hook runs checks without changing or staging files; run `mise run format` before committing. The pre-push hook runs the offline tests. CI runs the full gate on the pinned Python, tests Python 3.11–3.13 for compatibility, and tests the declared dependency floors with `--resolution lowest-direct` on Python 3.11.
126
+ The pre-commit hook formats staged files and runs the offline checks (`mise run check:local`). The pre-push hook runs the dependency audit (`mise run check:network`) and the offline tests. CI runs the full gate on the pinned Python, tests Python 3.11–3.15 for compatibility, and tests the declared dependency floors with `--resolution lowest-direct` on Python 3.11.
126
127
 
127
- A release tag must match the version in `pyproject.toml` (for example, `v0.1.0`). CD runs the same full gate for that tag and checks the live commands before publishing through PyPI Trusted Publishing. The live smoke check is a release check, not a pull-request gate.
128
+ A release tag must match the version in `pyproject.toml` (for example, `v0.1.0`). CD reruns every CI job for that tag (the gate, the Python versions, and the dependency floors) and checks the live commands before publishing through PyPI Trusted Publishing. The live smoke check is a release check, not a pull-request gate.
128
129
 
129
130
  ## License
130
131
 
@@ -1,9 +1,10 @@
1
1
  [project]
2
2
  name = "fmind"
3
- version = "2.0.3"
3
+ version = "2.0.5"
4
4
  description = "Read Médéric Hurier's (Fmind) portfolio from the terminal."
5
5
  readme = "README.md"
6
6
  license = "MIT"
7
+ license-files = ["LICENSE"]
7
8
  requires-python = ">=3.11"
8
9
  keywords = [
9
10
  "portfolio",
@@ -51,7 +52,7 @@ dev = [
51
52
  ]
52
53
 
53
54
  [build-system]
54
- requires = ["uv_build>=0.12.17,<0.13"]
55
+ requires = ["uv_build>=0.13.0,<0.14"]
55
56
  build-backend = "uv_build"
56
57
 
57
58
  [tool.uv.build-backend]
@@ -73,10 +74,23 @@ select = [
73
74
  "S",
74
75
  "SIM",
75
76
  "RUF",
77
+ "TID",
78
+ ]
79
+
80
+ [tool.ruff.lint.flake8-tidy-imports]
81
+ banned-module-level-imports = [
82
+ "fmind.mcp",
83
+ "httpx2",
84
+ "mcp",
85
+ "mcp_types",
76
86
  ]
77
87
 
78
88
  [tool.ruff.lint.per-file-ignores]
79
- "tests/**" = ["S101"]
89
+ "src/fmind/mcp.py" = ["TID253"]
90
+ "tests/**" = [
91
+ "S101",
92
+ "TID253",
93
+ ]
80
94
 
81
95
  [tool.ruff.format]
82
96
  docstring-code-format = true
@@ -1,10 +1,11 @@
1
1
  # https://packaging.python.org/en/latest/specifications/pyproject-toml/
2
2
  [project]
3
3
  name = "fmind"
4
- version = "2.0.3"
4
+ version = "2.0.5"
5
5
  description = "Read Médéric Hurier's (Fmind) portfolio from the terminal."
6
6
  readme = "README.md"
7
7
  license = "MIT"
8
+ license-files = ["LICENSE"]
8
9
  authors = [{ name = "Médéric Hurier", email = "contact@fmind.dev" }]
9
10
  requires-python = ">=3.11"
10
11
  keywords = ["portfolio", "cli", "fmind", "resume", "articles"]
@@ -40,7 +41,7 @@ dev = [
40
41
  ]
41
42
 
42
43
  [build-system]
43
- requires = ["uv_build>=0.12.17,<0.13"]
44
+ requires = ["uv_build>=0.13.0,<0.14"]
44
45
  build-backend = "uv_build"
45
46
 
46
47
  [tool.uv.build-backend]
@@ -51,9 +52,13 @@ module-root = "src"
51
52
  line-length = 120
52
53
  target-version = "py311"
53
54
  [tool.ruff.lint]
54
- select = ["E", "F", "I", "N", "UP", "B", "S", "SIM", "RUF"]
55
+ select = ["E", "F", "I", "N", "UP", "B", "S", "SIM", "RUF", "TID"]
56
+ [tool.ruff.lint.flake8-tidy-imports]
57
+ # Portfolio commands run without the optional `mcp` extra; only the bridge loads it.
58
+ banned-module-level-imports = ["fmind.mcp", "httpx2", "mcp", "mcp_types"]
55
59
  [tool.ruff.lint.per-file-ignores]
56
- "tests/**" = ["S101"] # assertions are the point of a test
60
+ "src/fmind/mcp.py" = ["TID253"] # the bridge is the extra's only importer
61
+ "tests/**" = ["S101", "TID253"] # assertions are the point of a test; tests install every extra
57
62
  [tool.ruff.format]
58
63
  docstring-code-format = true
59
64
 
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import http.client
6
6
  import json
7
+ import math
7
8
  import os
8
9
  import queue
9
10
  import re
@@ -20,6 +21,9 @@ PROFILE_URL = "https://www.fmind.dev/api/profile"
20
21
  TIMEOUT_SECONDS = 15.0
21
22
  # Bound memory use even when the origin serves an unexpected document.
22
23
  MAX_BYTES = 8 * 1024 * 1024
24
+ # `--json` re-indents forwarded fields, so output grows with the square of their
25
+ # nesting; the published profile nests four levels.
26
+ MAX_DEPTH = 32
23
27
  USER_AGENT = f"fmind/{__version__} (+https://github.com/fmind/cli)"
24
28
  # Slugs reach a URL, so only the shape the site actually mints is accepted.
25
29
  SLUG_PATTERN = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*\Z")
@@ -76,9 +80,14 @@ def article_url(slug: str, *, profile_url: str | None = None) -> str:
76
80
  return origin_url(f"/articles/{slug}.md", profile_url=profile_url)
77
81
 
78
82
 
83
+ def _profile_url() -> str:
84
+ """Return the configured profile endpoint, read at call time."""
85
+ return os.environ.get("FMIND_PROFILE_URL", PROFILE_URL)
86
+
87
+
79
88
  def origin_url(path: str, *, profile_url: str | None = None) -> str:
80
89
  """Resolve a website endpoint on the configured profile origin."""
81
- parts = _http_url(profile_url if profile_url is not None else os.environ.get("FMIND_PROFILE_URL", PROFILE_URL))
90
+ parts = _http_url(profile_url if profile_url is not None else _profile_url())
82
91
  return urllib.parse.urlunsplit((parts.scheme, parts.netloc, path, "", ""))
83
92
 
84
93
 
@@ -169,21 +178,25 @@ def _parse_profile(payload: bytes) -> dict[str, Any]:
169
178
  document = json.loads(payload, parse_constant=_reject_constant)
170
179
  except (ValueError, RecursionError) as error:
171
180
  raise FmindError("the profile endpoint did not return JSON") from error
172
- # Python's JSON decoder accepts lone surrogates. Check keys and future fields
173
- # too: JSON output forwards them even when the renderer does not consume them.
174
- pending = [document]
181
+ # Check keys and future fields too: JSON output forwards them even when the
182
+ # renderer does not consume them. The decoder accepts surrogates and can turn
183
+ # finite JSON literals such as 1e999 into infinity.
184
+ pending = [(document, 0)]
175
185
  while pending:
176
- value = pending.pop()
186
+ value, depth = pending.pop()
187
+ if depth > MAX_DEPTH:
188
+ raise FmindError(f"the profile endpoint returned a portfolio document nested over {MAX_DEPTH} levels")
189
+ if isinstance(value, float) and not math.isfinite(value):
190
+ raise FmindError("the profile endpoint returned a non-finite number")
177
191
  if isinstance(value, str):
178
192
  try:
179
193
  value.encode("utf-8")
180
194
  except UnicodeEncodeError as error:
181
195
  raise FmindError("the profile endpoint returned invalid Unicode") from error
182
196
  elif isinstance(value, dict):
183
- pending.extend(value)
184
- pending.extend(value.values())
197
+ pending.extend((item, depth + 1) for item in (*value, *value.values()))
185
198
  elif isinstance(value, list):
186
- pending.extend(value)
199
+ pending.extend((item, depth + 1) for item in value)
187
200
  _validate(document, PROFILE_SHAPE, "profile")
188
201
  links = document["thesis"].get("links")
189
202
  if links is not None:
@@ -206,8 +219,7 @@ def _parse_markdown(payload: bytes) -> str:
206
219
 
207
220
  def load_profile(*, url: str | None = None) -> dict[str, Any]:
208
221
  """Return the portfolio document behind every section command."""
209
- endpoint = url if url is not None else os.environ.get("FMIND_PROFILE_URL", PROFILE_URL)
210
- return _parse_profile(_download(endpoint))
222
+ return _parse_profile(_download(url if url is not None else _profile_url()))
211
223
 
212
224
 
213
225
  def load_article(slug: str, *, profile_url: str | None = None) -> str:
@@ -3,13 +3,14 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
+ import contextlib
6
7
  import json
7
8
  import os
8
9
  import shlex
9
10
  import shutil
10
11
  import subprocess
11
12
  import sys
12
- from typing import Annotated, Any
13
+ from typing import IO, Annotated, Any, cast
13
14
 
14
15
  import typer
15
16
  from rich.console import Console, RenderableType
@@ -82,17 +83,52 @@ class _SystemPager(Pager):
82
83
  # Like Git: respect an explicit LESS, otherwise keep colours (-R), skip
83
84
  # paging for short output (-F), and leave the text on screen (-X).
84
85
  environment = {**os.environ, "LESS": os.environ.get("LESS", "FRX")}
86
+ message = "could not display the article with PAGER; check PAGER or use PAGER=cat"
85
87
  try:
86
- subprocess.run( # noqa: S603
87
- self.command, input=content.encode(), env=environment, stderr=subprocess.DEVNULL, check=True
88
- )
89
- except (OSError, subprocess.CalledProcessError) as error:
90
- raise FmindError("could not display the article with PAGER; check PAGER or use PAGER=cat") from error
88
+ process = subprocess.Popen(self.command, stdin=subprocess.PIPE, stderr=subprocess.DEVNULL, env=environment) # noqa: S603
89
+ except OSError as error:
90
+ raise FmindError(message) from error
91
+ # Like the standard library's pager: Ctrl-C belongs to the pager. subprocess.run
92
+ # would kill it, leaving the terminal in raw mode, so wait for it to quit instead.
93
+ # Ctrl-C drops the unwritten rest, and a pager that quits early closes the pipe.
94
+ with (
95
+ contextlib.suppress(OSError),
96
+ cast("IO[bytes]", process.stdin) as pipe,
97
+ contextlib.suppress(KeyboardInterrupt),
98
+ ):
99
+ pipe.write(content.encode())
100
+ while True:
101
+ try:
102
+ code = process.wait()
103
+ break
104
+ except KeyboardInterrupt:
105
+ pass
106
+ if code != 0:
107
+ raise FmindError(message)
108
+
109
+
110
+ def _full_screen_terminal() -> bool:
111
+ """Whether TERM describes a terminal that a full-screen pager can drive."""
112
+ # Otherwise less stops at a "terminal is not fully functional" prompt that the
113
+ # hidden stderr turns into a blank screen: TERM unset or dumb, or missing from
114
+ # terminfo (TERM=xterm-kitty over SSH). setupterm also rejects generic and
115
+ # hardcopy entries such as `unknown`.
116
+ if os.environ.get("TERM", "") in {"", "dumb"}:
117
+ return False
118
+ try:
119
+ import curses # only the pager needs it, and Windows lacks it
120
+ except ImportError:
121
+ return True
122
+ try:
123
+ curses.setupterm()
124
+ except curses.error:
125
+ return False
126
+ return True
91
127
 
92
128
 
93
129
  def _pager_command() -> list[str] | None:
94
130
  """Return the pager for an interactive terminal, or None to print directly."""
95
- if not (sys.stdin.isatty() and sys.stdout.isatty()) or os.environ.get("TERM") == "dumb":
131
+ if not (sys.stdin.isatty() and sys.stdout.isatty() and _full_screen_terminal()):
96
132
  return None
97
133
  try:
98
134
  command = shlex.split(os.environ.get("PAGER", "less"))
@@ -122,16 +158,16 @@ def _emit(ctx: typer.Context, body: RenderableType, payload: Any, *, as_json: bo
122
158
  _write(CONTROL_PATTERN.sub(lambda match: f"\\u{ord(match.group()):04x}", text) + "\n")
123
159
  return
124
160
  out = _console(ctx)
125
- if not out.is_terminal:
126
- out.print(render.Trimmed(body), crop=False)
127
- return
128
- command = _pager_command() if page else None
161
+ # Trim on terminals too: forced colour (--color, FORCE_COLOR) makes Rich treat a
162
+ # pipe or file as a terminal, and line-end padding is invisible on a real one.
163
+ trimmed = render.Trimmed(body)
164
+ command = _pager_command() if page and out.is_terminal else None
129
165
  if command is None:
130
- out.print(body, crop=False)
166
+ out.print(trimmed, crop=False)
131
167
  return
132
168
  try:
133
169
  with out.pager(pager=_SystemPager(command), styles=True):
134
- out.print(body, crop=False)
170
+ out.print(trimmed, crop=False)
135
171
  except FmindError as error:
136
172
  raise _fail(str(error)) from error
137
173
 
@@ -226,8 +262,11 @@ def list_articles(ctx: typer.Context, limit: LimitOption = 6, as_json: JsonOptio
226
262
  @app.command()
227
263
  def search(
228
264
  ctx: typer.Context,
229
- # Optional, so filtering by tag alone needs no empty positional argument.
230
- query: Annotated[str, typer.Argument(help="Terms to match against titles, summaries, tags and slugs.")] = "",
265
+ # Optional, so filtering by tag alone needs no empty positional argument; several
266
+ # words need no quotes, so the hint printed by `read` runs as written.
267
+ query: Annotated[
268
+ list[str] | None, typer.Argument(help="Terms to match against titles, summaries, tags and slugs.")
269
+ ] = None,
231
270
  tag: Annotated[str | None, typer.Option("--tag", help="Restrict to one of the site's tags, such as Agent.")] = None,
232
271
  limit: LimitOption = 10,
233
272
  as_json: JsonOption = False,
@@ -238,7 +277,7 @@ def search(
238
277
  names = [entry["name"] for entry in doc["tags"]]
239
278
  if tag.lower() not in {name.lower() for name in names}:
240
279
  raise _fail(f"unknown tag {tag!r}; choose one of: {', '.join(names)}")
241
- found = articles.search(doc["articles"], query, tag=tag, limit=limit)
280
+ found = articles.search(doc["articles"], " ".join(query or []), tag=tag, limit=limit)
242
281
  footer = f"{len(found)} shown · {len(doc['articles'])} published · fmind read <slug> opens one"
243
282
  _emit(ctx, render.articles(found, footer=footer), found, as_json=as_json)
244
283
 
@@ -254,7 +293,8 @@ def read(
254
293
  doc = _doc()
255
294
  matches = articles.candidates(doc["articles"], slug.strip().lower())
256
295
  if not matches:
257
- raise _fail(f"no article matches {slug!r} — try: fmind search {slug}")
296
+ # Quote only what the shell would split or expand, so the hint runs as printed.
297
+ raise _fail(f"no article matches {slug!r} — try: fmind {shlex.join(['search', *slug.split()])}")
258
298
  if len(matches) > 1:
259
299
  listed = ", ".join(matches[:10])
260
300
  raise _fail(f"{slug!r} matches {len(matches)} articles: {listed}")
@@ -267,7 +307,8 @@ def read(
267
307
  if raw and not (as_json or ctx.find_root().params["as_json"]):
268
308
  _write(markdown)
269
309
  return
270
- payload = {"slug": resolved, "markdown": markdown, **(post or {})}
310
+ # The fetched article wins over any same-named field in the index entry.
311
+ payload = {**(post or {}), "slug": resolved, "markdown": markdown}
271
312
  _emit(ctx, render.article_body(markdown), payload, as_json=as_json, page=True)
272
313
 
273
314
 
@@ -20,17 +20,32 @@ from fmind import __version__
20
20
  from fmind.api import MAX_BYTES, TIMEOUT_SECONDS, USER_AGENT, FmindError, origin_url
21
21
 
22
22
 
23
+ class _ResponseError(httpx2.StreamError):
24
+ """A remote response broke a bound or the connection mid-body.
25
+
26
+ The SDK turns a stream error into one JSON-RPC error for that request; any
27
+ other exception escapes its transport task group and ends the whole bridge.
28
+ """
29
+
30
+
23
31
  class _BoundedStream(httpx2.AsyncByteStream):
24
- def __init__(self, stream: httpx2.AsyncByteStream) -> None:
32
+ def __init__(self, stream: httpx2.AsyncByteStream, deadline: float) -> None:
25
33
  self.stream = stream
34
+ self.deadline = deadline
26
35
 
27
36
  async def __aiter__(self) -> AsyncIterator[bytes]:
28
37
  size = 0
29
- async for chunk in self.stream:
30
- size += len(chunk)
31
- if size > MAX_BYTES:
32
- raise FmindError("the remote MCP response exceeded the size limit")
33
- yield chunk
38
+ try:
39
+ async with asyncio.timeout_at(self.deadline):
40
+ async for chunk in self.stream:
41
+ size += len(chunk)
42
+ if size > MAX_BYTES:
43
+ raise _ResponseError("the remote MCP response exceeded the size limit")
44
+ yield chunk
45
+ except TimeoutError as error:
46
+ raise _ResponseError("the remote MCP response exceeded its deadline") from error
47
+ except httpx2.TransportError as error:
48
+ raise _ResponseError("the remote MCP response was interrupted") from error
34
49
 
35
50
  async def aclose(self) -> None:
36
51
  await self.stream.aclose()
@@ -38,13 +53,25 @@ class _BoundedStream(httpx2.AsyncByteStream):
38
53
 
39
54
  class _BoundedTransport(httpx2.AsyncHTTPTransport):
40
55
  async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response:
41
- response = await super().handle_async_request(request)
56
+ # HTTPX read timeouts restart for every chunk. A legacy MCP server may
57
+ # ignore cancellation, so bound the entire HTTP exchange independently.
58
+ # Failures become gateway statuses: the SDK answers those with one
59
+ # JSON-RPC error, while a raised exception would end the whole bridge.
60
+ deadline = asyncio.get_running_loop().time() + TIMEOUT_SECONDS
61
+ try:
62
+ async with asyncio.timeout_at(deadline):
63
+ response = await super().handle_async_request(request)
64
+ except TimeoutError:
65
+ return httpx2.Response(504, request=request)
66
+ except httpx2.TransportError:
67
+ return httpx2.Response(502, request=request)
42
68
  if response.headers.get("content-encoding", "identity") != "identity":
69
+ # The client asks for identity, so a compressed body is a broken upstream.
43
70
  await response.aclose()
44
- raise FmindError("the remote MCP server ignored the uncompressed response requirement")
71
+ return httpx2.Response(502, request=request)
45
72
  if not isinstance(response.stream, httpx2.AsyncByteStream):
46
73
  raise FmindError("the remote MCP transport returned an invalid stream")
47
- response.stream = _BoundedStream(response.stream)
74
+ response.stream = _BoundedStream(response.stream, deadline)
48
75
  return response
49
76
 
50
77
 
@@ -91,6 +118,7 @@ async def serve() -> None:
91
118
  endpoint = origin_url("/mcp")
92
119
  # Protocol failures carry safe messages; SDK HTTP diagnostics can contain URLs.
93
120
  logging.getLogger("mcp").setLevel(logging.CRITICAL)
121
+ connected = False
94
122
  try:
95
123
  async with (
96
124
  httpx2.AsyncClient(
@@ -106,7 +134,12 @@ async def serve() -> None:
106
134
  stdio_server() as (reader, writer),
107
135
  ):
108
136
  server = create_bridge(remote)
137
+ connected = True
109
138
  await server.run(reader, writer, server.create_initialization_options())
110
139
  except Exception as error:
140
+ # After connecting, upstream failures are per-request JSON-RPC errors, so what
141
+ # remains (such as a host closing stdio) must not blame the remote server.
142
+ if connected:
143
+ raise FmindError("the MCP bridge stopped unexpectedly after connecting") from error
111
144
  message = "could not connect to the remote MCP server; check your connection and FMIND_PROFILE_URL"
112
145
  raise FmindError(message) from error
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from collections.abc import Iterable
5
+ from collections.abc import Iterable, Sequence
6
6
  from typing import Any
7
7
 
8
8
  from rich.console import Console, ConsoleOptions, Group, RenderableType, RenderResult
@@ -62,6 +62,11 @@ def _entry(*lines: RenderableType) -> Group:
62
62
  return Group(*lines, Text())
63
63
 
64
64
 
65
+ def _listing(blocks: Sequence[RenderableType], empty: str) -> RenderableType:
66
+ """The entries, or one line saying so when the website publishes none."""
67
+ return Group(*blocks) if blocks else Text(empty)
68
+
69
+
65
70
  def _rows(pairs: list[tuple[str, RenderableType]]) -> Table:
66
71
  """Lay out aligned key/value rows without visible borders."""
67
72
  table = Table.grid(padding=(0, 2))
@@ -87,16 +92,22 @@ def whoami(doc: dict[str, Any]) -> RenderableType:
87
92
  status.append("\n")
88
93
  status.append(service["title"], style="bold")
89
94
  status.append(f" — {service['badge']}")
90
- return _rows(
91
- [
92
- ("Name", Text(f"{meta['name']} ({meta['alternate_name']})", style="bold")),
93
- ("Role", Text(meta["job_title"])),
94
- ("Headline", Text(meta["headline_primary"])),
95
- ("Experience", mission),
96
- ("Status", status),
97
- ("Contact", _link(meta["email"])),
98
- ("Website", _link(meta["site_url"])),
99
- ]
95
+ return Group(
96
+ _rows(
97
+ [
98
+ ("Name", Text(f"{meta['name']} ({meta['alternate_name']})", style="bold")),
99
+ ("Role", Text(meta["job_title"])),
100
+ ("Headline", Text(meta["headline_primary"])),
101
+ ("Experience", mission),
102
+ ("Status", status),
103
+ ]
104
+ ),
105
+ # Table cells crop even no-wrap links. Keep these outside the grid,
106
+ # with the same 11-character label and two-space gap.
107
+ *(
108
+ Text.assemble((f"{label:<13}", ACCENT), _link(value), no_wrap=True, overflow="ignore")
109
+ for label, value in (("Contact", meta["email"]), ("Website", meta["site_url"]))
110
+ ),
100
111
  )
101
112
 
102
113
 
@@ -107,37 +118,36 @@ def about(doc: dict[str, Any]) -> RenderableType:
107
118
 
108
119
  def skills(doc: dict[str, Any]) -> RenderableType:
109
120
  """Show expertise without inventing command-line options or local labels."""
110
- return Group(*(_entry(Text(card["title"], style="bold"), Text(card["description"])) for card in doc["expertise"]))
121
+ blocks = [_entry(Text(card["title"], style="bold"), Text(card["description"])) for card in doc["expertise"]]
122
+ return _listing(blocks, "no expertise published")
111
123
 
112
124
 
113
125
  def experiences(doc: dict[str, Any]) -> RenderableType:
114
126
  """Engagements in the order published by the website."""
115
- return Group(
116
- *(
117
- _entry(
118
- Text(job["company"].upper(), style=ACCENT),
119
- Text(job["title"], style="bold"),
120
- Text(job["description"]),
121
- Text(" ".join(job["tags"])),
122
- )
123
- for job in doc["experience"]
127
+ blocks = [
128
+ _entry(
129
+ Text(job["company"].upper(), style=ACCENT),
130
+ Text(job["title"], style="bold"),
131
+ Text(job["description"]),
132
+ Text(" ".join(job["tags"])),
124
133
  )
125
- )
134
+ for job in doc["experience"]
135
+ ]
136
+ return _listing(blocks, "no experience published")
126
137
 
127
138
 
128
139
  def community(doc: dict[str, Any]) -> RenderableType:
129
140
  """Ambassador and advisory roles, with their published links."""
130
- return Group(
131
- *(
132
- _entry(
133
- Text(role["organization"], style=ACCENT),
134
- Text(role["role"], style="bold"),
135
- Text(role["description"]),
136
- _link(role["url"]),
137
- )
138
- for role in doc["leadership"]
141
+ blocks = [
142
+ _entry(
143
+ Text(role["organization"], style=ACCENT),
144
+ Text(role["role"], style="bold"),
145
+ Text(role["description"]),
146
+ _link(role["url"]),
139
147
  )
140
- )
148
+ for role in doc["leadership"]
149
+ ]
150
+ return _listing(blocks, "no community role published")
141
151
 
142
152
 
143
153
  def certifications(doc: dict[str, Any]) -> RenderableType:
@@ -174,7 +184,7 @@ def projects(doc: dict[str, Any], *, limit: int = 6) -> RenderableType:
174
184
  blocks += [
175
185
  _entry(Text(video["title"], style="bold"), Text(video["description"]), _link(video["url"])) for video in series
176
186
  ]
177
- return Group(*blocks)
187
+ return _listing(blocks, "no project published")
178
188
 
179
189
 
180
190
  def articles(posts: list[dict[str, Any]], *, footer: str = "") -> RenderableType:
@@ -236,19 +246,18 @@ def sites(doc: dict[str, Any]) -> RenderableType:
236
246
  )
237
247
  for page in doc["site_pages"]
238
248
  ]
239
- return Group(*blocks) if blocks else Text("no interactive site published")
249
+ return _listing(blocks, "no interactive site published")
240
250
 
241
251
 
242
252
  def hire(doc: dict[str, Any]) -> RenderableType:
243
253
  """What can be booked right now."""
244
- return Group(
245
- *(
246
- _entry(
247
- Text(service["title"], style="bold"),
248
- Text(service["description"]),
249
- Text(service["badge"], style="bold"),
250
- _link(service["cta_url"]),
251
- )
252
- for service in doc["services"]
254
+ blocks = [
255
+ _entry(
256
+ Text(service["title"], style="bold"),
257
+ Text(service["description"]),
258
+ Text(service["badge"], style="bold"),
259
+ _link(service["cta_url"]),
253
260
  )
254
- )
261
+ for service in doc["services"]
262
+ ]
263
+ return _listing(blocks, "no service published")
File without changes
File without changes
File without changes