diff --git a/dataiku_mcp/tools/cobuild.py b/dataiku_mcp/tools/cobuild.py index a4ffb2b4..669d5fbe 100644 --- a/dataiku_mcp/tools/cobuild.py +++ b/dataiku_mcp/tools/cobuild.py @@ -31,6 +31,7 @@ from ..config import request from ..executors import run_blocking, run_cobuild_blocking from ..server import DSS_INDEPENDENT_TOOL_TAG, mcp +from .utils.cobuild_links import extract_object_links from dataiku_mcp.utils.serialization import columnar, compact_json, omit_empty from dataiku_mcp.utils.validation import ( require_non_empty_string as _require_non_empty_string, @@ -114,6 +115,7 @@ def _terminal_turn_result( or response_type == "ask_question_to_user_request" ) is_error = bool(getattr(response, "is_error", False)) + message = str(getattr(response, "message", "")) result = { "status": "failed" if is_error else "completed", "conversation_id": conversation_id, @@ -121,7 +123,10 @@ def _terminal_turn_result( "instance_name": entry.instance_name, "project_key": entry.project_key, "project_url": _project_url(entry), - "message": str(getattr(response, "message", "")), + "message": message, + "object_links": extract_object_links( + message, entry.instance_url, entry.project_key + ), "response_type": response_type, "is_error": is_error, "is_confirmation_request": confirmation_requested, diff --git a/dataiku_mcp/tools/utils/cobuild_links.py b/dataiku_mcp/tools/utils/cobuild_links.py new file mode 100644 index 00000000..94ab8cbb --- /dev/null +++ b/dataiku_mcp/tools/utils/cobuild_links.py @@ -0,0 +1,102 @@ +# Copyright 2026 Dataiku SAS +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Resolve Cobuild's inline Markdown object references to Dataiku UI links.""" + +import re +from urllib.parse import quote + +# Dataiku's StateUtils.href.dssObject routes (including extended saved-model types). +# Keep IDs as path segments; no object lookup or display-name slug is required. +_OBJECT_ROUTES = { + "DATASET": "datasets/{id}/explore/", + "RECIPE": "recipes/{id}/", + "ANALYSIS": "analysis/{id}/script/", + "WEB_APP": "webapps/{id}_/view", + "DASHBOARD": "dashboards/{id}_/view/", + "INSIGHT": "dashboards/insights/{id}_/view", + "SAVED_MODEL": "savedmodels/{id}/versions/", + "AI_AGENT": "savedmodels/{id}/versions/", + "FINE_TUNED_MODEL": "savedmodels/{id}/versions/", + "GEN_AI_MODEL": "savedmodels/{id}/versions/", + "MODEL_EVALUATION_STORE": "modelevaluationstores/{id}/evaluations/", + "GENAI_EVALUATION_STORE": "genaievaluationstores/{id}/evaluations/", + "MANAGED_FOLDER": "managedfolder/{id}/view/", + "RETRIEVABLE_KNOWLEDGE": "knowledge-bank/{id}/usage/", + "SCENARIO": "scenarios/{id}/runs/list/", + "ARTICLE": "wiki/{id}", + "JUPYTER_NOTEBOOK": "notebooks/jupyter/{id}/", + "SQL_NOTEBOOK": "notebooks/sql/{id}/", + "SEARCH_NOTEBOOK": "notebooks/search/{id}/", + "LABELING_TASK": "labelingtasks/{id}", + "FLOW_ZONE": "flow/?zoneId={id}", +} +_MARKDOWN_TOKEN = re.compile( + r"(?P\\.)" + r"|^ {0,3}(?P`{3,}|~{3,})[^\n]*(?:\n|$)" + r"|(?P`+)" + r"|(?P!?)\[(?:\\.|[^\[\]\\])*\]" + r"\((?P[A-Z_]+):(?P(?:\\.|[^)\\\r\n])+)\)", + re.IGNORECASE | re.MULTILINE, +) + + +def _inline_object_references(message: str): + """Scan supported inline links, skipping escapes, images, and Markdown code.""" + position = 0 + while match := _MARKDOWN_TOKEN.search(message, position): + position = match.end() + if match["fence"]: + fence = match["fence"] + closing = re.compile( + r"^ {0,3}" + re.escape(fence[0]) + "{" + str(len(fence)) + r",}[ \t]*$", + re.MULTILINE, + ).search(message, position) + position = closing.end() if closing else len(message) + elif match["code"]: + # Code spans close only on a run of exactly the opening length. + closing = re.compile( + r"(? list[dict[str, str]]: + """Return unique resolved links while leaving the original message untouched.""" + links = [] + seen = set() + for match in _inline_object_references(message): + object_type = match["object_type"].upper() + route = _OBJECT_ROUTES.get(object_type) + if route is None: + continue + smart_id = re.sub(r"\\(.)", r"\1", match["object_id"]) + target_project, separator, object_id = smart_id.partition(".") + if not separator: + target_project, object_id = project_key, smart_id + if not target_project or not object_id or object_id in {".", ".."}: + continue + url = ( + f"{instance_url.rstrip('/')}/projects/{quote(target_project, safe='')}/" + + route.format(id=quote(object_id, safe="")) + ) + if url not in seen: + links.append({"reference": f"{object_type}:{smart_id}", "url": url}) + seen.add(url) + return links diff --git a/skills/dataiku-headless/references/cobuild.md b/skills/dataiku-headless/references/cobuild.md index 31e8dcda..164a82c5 100644 --- a/skills/dataiku-headless/references/cobuild.md +++ b/skills/dataiku-headless/references/cobuild.md @@ -19,7 +19,7 @@ Use this guide as the default path for project-level asset creation. This includ - Cobuild can inspect project context, propose changes, and make permitted changes through the same conversation. - Deletion confirmations and questions are separate response steps bound to their exact `turn_id`. A request to edit does not authorize a broader or unexpected deletion. - Conversations and turns are retained only in the MCP server process and are lost when it restarts. -- Every Cobuild payload carries `project_url`, the Dataiku UI URL of the conversation's project on the instance that conversation is pinned to. Dataiku exposes no per-conversation URL: Cobuild opens as a panel inside the project, so `project_url` points at the project and the user opens Cobuild from there. +- Responses include `project_url` for the project Flow and may include `object_links` with URLs for specific assets. ## When To Use This Skill @@ -79,7 +79,7 @@ Do not use this guide when: - Use `allow_edit_project=true` only when the user has explicitly requested a creation or modification. - `send_cobuild_message` defaults `allow_edit_project` to `false`. - A terminal turn may return `is_confirmation_request=true`, with deletion details in `objects_to_delete` and `deletion_impacts`, or `is_question_request=true`, with answer constraints in `question`. -- Treat `project_url` as an optional link for viewing the conversation in Dataiku. Surface it when the user asks to inspect or continue the conversation in the UI. +- After verifying each substantial milestone, share the relevant asset URLs from the response, falling back to `project_url` when none are available. - Before answering a confirmation or question, always retrieve and inspect its exact current `turn_id` with `get_cobuild_turn_status`. - Answer confirmations only with the exact current `turn_id`. Old, duplicate, and mismatched turn IDs are rejected. - Answer questions only with their exact current `turn_id` and an explicit `answers` list. Use `answers=[]` with `rejected=true` to decline. diff --git a/tests/test_cobuild.py b/tests/test_cobuild.py index 87e3c8d2..81a84607 100644 --- a/tests/test_cobuild.py +++ b/tests/test_cobuild.py @@ -597,3 +597,38 @@ async def scenario(): assert (await start())["project_url"] == PROJECT_URL run(scenario()) + + +def test_terminal_object_links_preserve_message_and_pinned_instance(environment): + client, active_instance = environment + message = "Created [sales](WEB_APP:PROJECT.app) and [clean](RECIPE:clean)." + client.conversation.next_send = Response(message) + + async def scenario(): + await start() + # The instance URL may change while the retained conversation still + # belongs to the same instance name; use its captured URL for links. + active_instance["url"] = "https://b.example.com" + result = await send(allow_edit_project=True) + assert result["message"] == message + assert result["object_links"] == [ + { + "reference": "WEB_APP:PROJECT.app", + "url": "https://a.example.com/projects/PROJECT/webapps/app_/view", + }, + { + "reference": "RECIPE:clean", + "url": "https://a.example.com/projects/PROJECT/recipes/clean/", + }, + ] + assert (await poll(result["turn_id"]))["object_links"] == result["object_links"] + + run(scenario()) + + +def test_terminal_response_without_object_links_omits_the_field(environment): + async def scenario(): + await start() + assert "object_links" not in await send() + + run(scenario()) diff --git a/tests/test_cobuild_links.py b/tests/test_cobuild_links.py new file mode 100644 index 00000000..e0f588bd --- /dev/null +++ b/tests/test_cobuild_links.py @@ -0,0 +1,82 @@ +# Copyright 2026 Dataiku SAS +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Cobuild object links follow Dataiku UI routes without SDK lookups.""" + +import pytest + +from dataiku_mcp.tools.utils.cobuild_links import extract_object_links + + +@pytest.mark.parametrize( + ("object_type", "path"), + [ + ("WEB_APP", "webapps/item_/view"), + ("RECIPE", "recipes/item/"), + ("ANALYSIS", "analysis/item/script/"), + ("DATASET", "datasets/item/explore/"), + ("DASHBOARD", "dashboards/item_/view/"), + ("INSIGHT", "dashboards/insights/item_/view"), + ("AI_AGENT", "savedmodels/item/versions/"), + ("FINE_TUNED_MODEL", "savedmodels/item/versions/"), + ("GEN_AI_MODEL", "savedmodels/item/versions/"), + ("GENAI_EVALUATION_STORE", "genaievaluationstores/item/evaluations/"), + ("RETRIEVABLE_KNOWLEDGE", "knowledge-bank/item/usage/"), + ("FLOW_ZONE", "flow/?zoneId=item"), + ], +) +def test_local_object_routes(object_type, path): + assert extract_object_links( + f"Created [an object]({object_type}:item).", "https://example.com", "PROJECT" + ) == [ + { + "reference": f"{object_type}:item", + "url": f"https://example.com/projects/PROJECT/{path}", + } + ] + + +def test_qualified_ids_base_path_escaping_and_duplicate_targets(): + message = ( + "[app](web_app:OTHER.app) and [again](WEB_APP:OTHER.app)\n" + r"[notebook](JUPYTER_NOTEBOOK:PROJECT.sales \(draft\)/?#)" + ) + assert extract_object_links(message, "https://example.com/dss/", "PROJECT") == [ + { + "reference": "WEB_APP:OTHER.app", + "url": "https://example.com/dss/projects/OTHER/webapps/app_/view", + }, + { + "reference": "JUPYTER_NOTEBOOK:PROJECT.sales (draft)/?#", + "url": "https://example.com/dss/projects/PROJECT/notebooks/jupyter/" + "sales%20%28draft%29%2F%3F%23/", + }, + ] + + +@pytest.mark.parametrize( + "message", + [ + "Nothing created.", + "[external](https://example.org/path)", + "[unknown](FUTURE_TYPE:PROJECT.item)", + "[empty](WEB_APP:)", + "[empty project](WEB_APP:.item)", + "[empty id](WEB_APP:PROJECT.)", + "[dot segment](RECIPE:PROJECT...)", + "[unfinished](WEB_APP:PROJECT.item", + ], +) +def test_unsupported_or_invalid_references_do_not_invent_links(message): + assert extract_object_links(message, "https://example.com", "PROJECT") == []