Skip to content

refactor(site): use next-sdk and next-remoter to intelligentize the official website. #3657

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from

Conversation

shenjunjian
Copy link
Collaborator

@shenjunjian shenjunjian commented Aug 20, 2025

PR

fix(site): 移除官网原来的next-sdk, robot的实现
fix(site): 对接新版本的next-sdk

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Integrated a Tiny Remoter panel gated by a remote session and added an app-wide showPreview(url) provider.
    • Added a script to start the example site only.
  • Refactor

    • Removed legacy Tiny Robot chat UI, markdown renderer, and LLM configuration flows; simplified MCP docs to accept data via prop and updated MCP tab visibility.
    • Introduced a composable that manages remote session state.
  • Chores

    • Updated SDK dependencies and added a remoter dependency.

Copy link

coderabbitai bot commented Aug 20, 2025

Walkthrough

Replaces the Tiny Robot chat and local LLM tooling with a TinyRemoter WebMCP flow: adds a remoter composable, renders via a sessionId, removes chat components/composables/agent provider and related utilities/styles, updates MCP docs data flow, and adjusts dependencies and a package script.

Changes

Cohort / File(s) Summary
WebMCP remoter integration
examples/sites/src/composable/useTinyRemoter.ts, examples/sites/src/App.vue
Added useTinyRemoter to create/connect WebMcpServer and WebMcpClient, obtain sessionId (webMcpSessionId) and expose server/client state; App.vue invokes it, renders <tiny-remoter :sessionId="webMcpSessionId"> when set, and provides showPreview for the preview modal.
MCP docs data flow
examples/sites/src/components/mcp-docs.vue, examples/sites/src/views/components-doc/common.vue
McpDocs now accepts a data prop (Array) and uses provided name; common.vue computes capName and mcpInfo from mcpTools and passes :data="mcpInfo" and :name="capName", updates MCP tab visibility and cleans up cmpAnchorDataCallback on unmount.
Removal of Tiny Robot chat & markdown
examples/sites/src/components/tiny-robot-chat.vue, examples/sites/src/components/ReactiveMarkdown.vue, examples/sites/src/composable/useTinyRobot.ts, examples/sites/src/composable/agentModelProvider.ts
Deleted Tiny Robot UI component, ReactiveMarkdown renderer, useTinyRobot composable, and AgentModelProvider (agentModelProvider.ts) — removing local LLM/chat integration, streaming/provider code, and markdown rendering component.
Utilities and bootstrap cleanup
examples/sites/src/composable/utils.ts, examples/sites/src/main.js
Removed showTinyRobot, isEnvLLMDefined, and isLocalLLMDefined exports from utils; removed Tiny Robot dialog stylesheet import from main.js.
Dependencies and scripts
examples/sites/package.json, package.json
In examples/sites package.json added @opentiny/next-remoter and bumped @opentiny/next-sdk and @opentiny/tiny-vue-mcp; at repo root package.json added site:only script to run pnpm -C examples/sites start.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant App as App.vue
  participant Remoter as useTinyRemoter()
  participant Server as WebMcpServer
  participant Client as WebMcpClient
  participant Agent as Remote Agent (AGENT_ROOT/mcp)
  participant UI as <tiny-remoter>

  User->>App: Load page
  App->>Remoter: await useTinyRemoter()
  Remoter->>Server: init(capabilities, register tool)
  Remoter->>Client: init(capabilities, attach handlers)
  Remoter->>Client: connect(AGENT_ROOT + "mcp")
  Client->>Agent: establish session
  Agent-->>Client: return sessionId
  Remoter-->>App: set webMcpSessionId
  App->>UI: render when sessionId present
  User->>UI: interact (requests / tool calls)
  UI->>Client: send via session
  Client->>Agent: forward requests
  Agent-->>Client: stream responses/events
  Client-->>UI: stream updates
  note over Client,Server: cleanup on pagehide/unload
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • kagol

Poem

A rabbit unplugged the robot’s chat,
Launched a remoter — tiny and spry,
Sessions humming across the net,
Preview opens, components fly.
Hop, connect, a new tab’s delight — 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch shen/remove-old-next-sdk

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added the refactoring Refactoring (重构) label Aug 20, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (10)
package.json (1)

45-45: Add docs/guardrails for the new site:only script.

Starting the site without building entry/theme may break if consumers expect built artifacts. Consider either documenting preconditions (run build:entry + theme build first) or wiring a lightweight pre-step.

Apply this diff to add a fast guard:

 "scripts": {
   "// ---------- 启动官网文档 ----------": "",
   "site": "pnpm build:entry && pnpm -C packages/theme build && pnpm -C examples/sites start",
   "site:open": "pnpm build:entry && pnpm -C packages/theme build && pnpm -C examples/sites start:open",
-  "site:only": "pnpm -C examples/sites start",
+  "pre:site:only": "pnpm -C packages/theme build:fast || true",
+  "site:only": "pnpm -C examples/sites start",
examples/sites/package.json (1)

30-36: Remove unused tiny-robot dependencies
A search through all JS/TS files under examples/sites found no references to the Tiny Robot packages. You can safely drop these to avoid confusion and slim down installs:

• examples/sites/package.json

   "dependencies": {
     "@docsearch/css": "^3.8.0",
     "@docsearch/js": "^3.8.0",
     "@docsearch/react": "npm:@docsearch/css",
     "@opentiny/next-remoter": "^0.0.1-alpha.10",
     "@opentiny/next-sdk": "^0.1.1",
-    "@opentiny/tiny-robot": "0.3.0-alpha.3",
-    "@opentiny/tiny-robot-kit": "0.3.0-alpha.3",
-    "@opentiny/tiny-robot-svgs": "0.3.0-alpha.3",
     "@opentiny/tiny-vue-mcp": "^0.0.3",
     "@opentiny/utils": "workspace:~",
   }
examples/sites/src/components/mcp-docs.vue (1)

17-20: Minor type-safety improvement (optional).

If you’re open to TS here, annotate props for better DX/autocomplete.

Apply this change if you switch to TS:

-<script setup>
+<script setup lang="ts">
 import { TinyGrid, TinyGridColumn } from '@opentiny/vue'

-const props = defineProps({
-  name: String,
-  data: Array
-})
+const props = defineProps<{
+  name: string
+  data: Array<{ name: string; param: string; desc: string }>
+}>()
examples/sites/src/views/components-doc/common.vue (1)

460-478: Avoid relying on Zod’s private _def internals.

Accessing _def.innerType._def.typeName and _def.description is brittle across Zod versions. A minor change upstream can break this UI.

Consider:

  • Prefer top-level schema you own that already includes a serializable type/description.
  • Or transform Zod schema to JSON Schema using zod-to-json-schema at build time, then read type/description from the JSON.
  • Short-term: guard aggressively to avoid runtime errors.

Minimal hardening:

-  const schema = mcpTools.components[capName.value]?.paramsSchema
+  const schema = mcpTools.components?.[capName.value]?.paramsSchema
   if (schema) {
     return Object.keys(schema).map((name) => {
       const item = schema[name]
       return {
         name,
-        param: item._def?.innerType?._def?.typeName || '',
-        desc: item._def?.description || ''
+        // Prefer safer fallbacks
+        param: (item as any)?._def?.innerType?._def?.typeName || (item as any)?._def?.typeName || '',
+        desc: (item as any)?._def?.description || ''
       }
     })
   }
examples/sites/src/composable/useTinyRemoter.ts (3)

9-13: Unify state holders: prefer refs or plain lets consistently.

Mixing { value: ... } objects and Vue refs is confusing. Server/client don’t need reactivity; the sessionId does.

-export const webMcpServer: { value: null | WebMcpServer } = { value: null }
-export const webMcpClient: { value: null | WebMcpClient } = { value: null }
-export const webMcpSessionId: { value: null | string } = ref('')
+export let webMcpServer: WebMcpServer | null = null
+export let webMcpClient: WebMcpClient | null = null
+export const webMcpSessionId = ref<string | null>(null)
@@
-  webMcpServer.value = server
+  webMcpServer = server
@@
-  webMcpClient.value = client
+  webMcpClient = client
@@
-  webMcpSessionId.value = sessionId
+  webMcpSessionId.value = sessionId

84-113: Typo in tool name: swtich-routerswitch-router (keep alias if needed).

Tool names are user/agent-facing. The typo can hinder discoverability.

To avoid breaking existing prompts, register an alias temporarily:

-  server.registerTool(
-    'swtich-router',
+  // Keep the misspelled name as a temporary alias for compatibility
+  server.registerTool(
+    'switch-router',
     {
       title: 'router',
       description: '可以帮用户跳转到文档页面,组件示例的总页面或组件API文档页面,或组件库的概览页面',
       inputSchema: {
         key: z.string().describe('跳转页面路径'),
         type: z
           .enum(['components', 'docs', 'overview', 'features'])
           .describe('跳转页面类型,比如:组件的页面,文档的页面,组件的概览页面'),
-        isOpenApi: z.boolean().describe('跳转到组件页面时,是否打开API文档')
+        isOpenApi: z.boolean().optional().describe('跳转到组件页面时,是否打开API文档')
       }
     },
@@
   )
+  // Backward-compatibility alias
+  server.registerTool('swtich-router', { title: 'router (alias)' } as any, async (input) =>
+    (server as any).tools.get('switch-router').handler(input)
+  )

58-59: Bind onPagehide to avoid context loss (defensive).

If onPagehide relies on this, passing it directly can lose context.

-  window.addEventListener('pagehide', client.onPagehide)
+  window.addEventListener('pagehide', () => client.onPagehide())
examples/sites/src/App.vue (3)

9-9: Key the TinyRemoter by session to avoid stale internal state on ID changes

If webMcpSessionId is regenerated, keying the component ensures a clean remount. Optionally, render a lightweight placeholder while initializing to avoid a blank area.

-      <tiny-remoter v-if="webMcpSessionId" :sessionId="webMcpSessionId"> </tiny-remoter>
+      <tiny-remoter
+        v-if="webMcpSessionId"
+        :key="webMcpSessionId"
+        :sessionId="webMcpSessionId"
+      />

15-20: Remove unused iconClose import

You’re using the <tiny-icon-close> component directly; the imported iconClose factory isn’t used. Drop the import to reduce bundle size and avoid dead code.

 import { onMounted, provide, ref } from 'vue'
 import { TinyConfigProvider, TinyModal } from '@opentiny/vue'
-import { iconClose } from '@opentiny/vue-icon'
 import { TinyRemoter } from '@opentiny/next-remoter'
 import '@opentiny/next-remoter/dist/style.css'
 import { useTinyRemoter, webMcpSessionId } from './composable/useTinyRemoter'

26-28: Rename modalSHow → modalShow for clarity; remove unused tinyIconClose; type previewUrl

  • The current casing “modalSHow” is hard to read and non-idiomatic. Prefer “modalShow.”
  • tinyIconClose is unused once you render <tiny-icon-close> directly.
  • Add a string type and a safe default for previewUrl to avoid undefined.
-const previewUrl = ref(import.meta.env.VITE_PLAYGROUND_URL)
-const tinyIconClose = iconClose()
+const previewUrl = ref<string>(import.meta.env.VITE_PLAYGROUND_URL || '')

Outside this range, also rename the ref and its usages:

// script
-const modalSHow = ref(false)
+const modalShow = ref(false)

// template
-<tiny-modal ... v-model="modalSHow" ...>
-  <tiny-icon-close class="close-icon" @click="modalSHow = false" />
-  <iframe v-if="modalSHow" ... />
+</tiny-modal ... v-model="modalShow" ...>
+  <tiny-icon-close class="close-icon" @click="modalShow = false" />
+  <iframe v-if="modalShow" ... />
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4366672 and 87d2ab2.

📒 Files selected for processing (12)
  • examples/sites/package.json (1 hunks)
  • examples/sites/src/App.vue (2 hunks)
  • examples/sites/src/components/ReactiveMarkdown.vue (0 hunks)
  • examples/sites/src/components/mcp-docs.vue (2 hunks)
  • examples/sites/src/components/tiny-robot-chat.vue (0 hunks)
  • examples/sites/src/composable/agentModelProvider.ts (0 hunks)
  • examples/sites/src/composable/useTinyRemoter.ts (1 hunks)
  • examples/sites/src/composable/useTinyRobot.ts (0 hunks)
  • examples/sites/src/composable/utils.ts (0 hunks)
  • examples/sites/src/main.js (0 hunks)
  • examples/sites/src/views/components-doc/common.vue (3 hunks)
  • package.json (1 hunks)
💤 Files with no reviewable changes (6)
  • examples/sites/src/main.js
  • examples/sites/src/components/tiny-robot-chat.vue
  • examples/sites/src/composable/useTinyRobot.ts
  • examples/sites/src/components/ReactiveMarkdown.vue
  • examples/sites/src/composable/agentModelProvider.ts
  • examples/sites/src/composable/utils.ts
🔇 Additional comments (7)
examples/sites/src/components/mcp-docs.vue (1)

4-6: Prop-driven MCP table is simpler and clearer.

Using name and data props removes hidden coupling and makes the component more reusable. LGTM.

examples/sites/src/views/components-doc/common.vue (3)

69-71: MCP tab gating + prop handoff to McpDocs looks right.

Showing the tab only when there’s MCP data prevents empty UI. Passing computed name/data aligns with the refactor.


115-118: Confirm getTinyVueMcpConfig({ t: null }) tolerates null.

If the MCP config factory expects a translator fn, passing null may throw under some code paths.

If it’s not null-safe, use a no-op translator:

-import { getTinyVueMcpConfig } from '@opentiny/tiny-vue-mcp'
+import { getTinyVueMcpConfig } from '@opentiny/tiny-vue-mcp'
+const t = (s: string) => s
-const mcpTools = getTinyVueMcpConfig({ t: null })
+const mcpTools = getTinyVueMcpConfig({ t })

454-458: Good: lifecycle cleanup for the anchor callback.

Setting and unsetting the global callback reduces leaks and stale references.

examples/sites/src/composable/useTinyRemoter.ts (1)

38-46: Confirm sequential connect() semantics on WebMcpClient

It looks like in useTinyRemoter.ts we call client.connect(clientTransport) and then immediately await client.connect({ url:…, agent: true }) on the same instance. Verify that:

  • The second connect() call adds to the existing transport rather than replacing it.
  • If it replaces, you’ll lose the local message‐channel link (roots/listChanged, sampling, elicitation).
  • If the SDK expects a separate “remoter bridge” or a new client instance for remote connections, adjust accordingly.

Locations to check:

  • examples/sites/src/composable/useTinyRemoter.ts lines 45–49
examples/sites/src/App.vue (2)

22-22: Theme hook import looks good

Using useTheme to drive designConfig and currentThemeKey is consistent with the provider usage.


24-24: Initializing the remoter early is appropriate

Calling useTinyRemoter() at setup-time ensures webMcpSessionId is available for gating the UI.

Comment on lines +46 to 50
// 多端的预览图
provide('showPreview', (url) => {
previewUrl.value = url
modalSHow.value = true
})
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Sanitize preview URLs and sandbox the iframe to mitigate XSS/navigation risks

showPreview directly assigns an unvalidated URL to an iframe src, and the iframe lacks a sandbox. A malicious or malformed URL (javascript: / data: / cross-origin) could execute or navigate unexpectedly. Validate/whitelist the origin and sandbox the iframe.

Minimal type improvement within this hunk:

-// 多端的预览图
-provide('showPreview', (url) => {
+// 多端的预览图
+provide('showPreview', (url: string) => {
   previewUrl.value = url
   modalSHow.value = true
 })

Outside this range, add URL validation and apply it in the provider:

// Add near other utilities
const toSafePreviewUrl = (input: string): string => {
  try {
    const base = import.meta.env.VITE_PLAYGROUND_URL || window.location.origin
    const u = new URL(input, base)
    const allowed = new URL(base).origin
    return u.origin === allowed ? u.toString() : allowed
  } catch {
    return import.meta.env.VITE_PLAYGROUND_URL || window.location.origin
  }
}

// Then change the provider assignment:
previewUrl.value = toSafePreviewUrl(url)

And sandbox the iframe (template, same block):

<iframe
  v-if="modalShow"
  width="100%"
  height="100%"
  :src="previewUrl"
  frameborder="0"
  sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
  referrerpolicy="no-referrer"
  loading="lazy"
/>

Adjust sandbox allowances to match your preview features.

🤖 Prompt for AI Agents
In examples/sites/src/App.vue around lines 46 to 50, showPreview currently
assigns unvalidated URLs directly to previewUrl and the iframe is unsandboxed;
add a small URL sanitizer utility (toSafePreviewUrl) near other utilities that
resolves the input against a trusted base (VITE_PLAYGROUND_URL or
window.location.origin), returns the input only if the origin matches the
allowed origin, and falls back to the trusted base on error, then call
previewUrl.value = toSafePreviewUrl(url) in the provider; also update the iframe
markup to include a sandbox attribute with minimal required allowances (e.g.
allow-scripts, allow-same-origin, allow-forms, allow-popups as needed), add
referrerpolicy="no-referrer" and loading="lazy" for safer, performant embedding,
and ensure the modalShow/modalSHow binding name is used consistently.

zzcr
zzcr previously approved these changes Aug 20, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
examples/sites/src/composable/useTinyRemoter.ts (1)

6-6: Stop hard-coding AGENT_ROOT and gate remote connect (security/ops).

Good job removing the fixed sessionId. The root endpoint is still hard-coded and the client always dials the remote in all environments. This risks leaking traffic to prod/trial from local/dev and makes the site non-portable.

Apply this diff to source the root from env and skip remote dialing if not configured:

-export const AGENT_ROOT = 'https://agent.opentiny.design/api/v1/webmcp-trial/'
+export const AGENT_ROOT =
+  (import.meta as any)?.env?.VITE_WEBMCP_ROOT ??
+  (window as any)?.__WEBMCP_ROOT ??
+  ''
@@
-  // 不能传入固定的sessionId, 让它每次自动生成一个。
-  const { sessionId } = await client.connect({
-    url: AGENT_ROOT + 'mcp',
-    agent: true,
-    onError: (error: Error) => {
-      console.error('Connect proxy error:', error)
-    }
-  })
-  webMcpSessionId.value = sessionId
+  // 不能传入固定的sessionId, 让它每次自动生成一个。
+  // 若未配置 AGENT_ROOT,跳过远端连接,避免本地环境误连线上/试用环境。
+  if (!AGENT_ROOT) {
+    console.warn('[TinyRemoter] AGENT_ROOT is empty; skipping remote MCP connection')
+  } else {
+    const { sessionId } = await client.connect({
+      url: AGENT_ROOT.replace(/\/?$/, '/') + 'mcp',
+      agent: true,
+      onError: (error: Error) => {
+        console.error('Connect proxy error:', error)
+      }
+    })
+    webMcpSessionId.value = sessionId
+  }

Also applies to: 46-55

🧹 Nitpick comments (6)
examples/sites/src/composable/useTinyRemoter.ts (6)

9-11: Unify reactivity and types for exported holders (use proper Vue refs).

webMcpServer/webMcpClient are plain objects, but webMcpSessionId is a Vue ref with a looser structural type. Make all three proper refs and type sessionId as string | null (initialize with null for clearer semantics).

-export const webMcpServer: { value: null | WebMcpServer } = { value: null }
-export const webMcpClient: { value: null | WebMcpClient } = { value: null }
-export const webMcpSessionId: { value: null | string } = ref('')
+export const webMcpServer = ref<WebMcpServer | null>(null)
+export const webMcpClient = ref<WebMcpClient | null>(null)
+export const webMcpSessionId = ref<string | null>(null)

Note: If App.vue relies on truthiness checks, nothing changes; but if it compares to empty string, adjust to handle null.


32-36: Add client transport error handling and wrap connect calls in try/catch.

You handle serverTransport.onerror, but not clientTransport.onerror, and none of the connect calls are guarded. A failed connect can reject and bubble, impacting UX.

   serverTransport.onerror = (error) => {
     console.error(`ServerTransport error:`, error)
   }
-  await server.connect(serverTransport)
+  try {
+    await server.connect(serverTransport)
+  } catch (e) {
+    console.error('Server connect failed:', e)
+  }
@@
-  await client.connect(clientTransport)
+  clientTransport.onerror = (error) => {
+    console.error(`ClientTransport error:`, error)
+  }
+  try {
+    await client.connect(clientTransport)
+  } catch (e) {
+    console.error('Client connect failed:', e)
+  }

Also applies to: 37-45


67-71: Use the correct MIME type for JSON payload.

The resource returns JSON via JSON.stringify but declares text/plain. Prefer application/json for better downstream handling.

-      mimeType: 'text/plain'
+      mimeType: 'application/json'

82-95: Typo in tool name: “swtich-router” → “switch-router”. Verify external coupling.

If the tool name is part of a contract with the remote agent, renaming could break flows. Either register both names or migrate consumers first.

Proposed change:

-  server.registerTool(
-    'swtich-router',
+  server.registerTool(
+    'switch-router',

If backward compatibility is required, also register an alias outside this range:

// Optional alias (outside diff range)
server.registerTool('swtich-router', /* same schema */, sameHandler)

96-101: Harden route construction for edge cases (array params/missing theme).

params.theme can be string | string[]. Also handle theme not found in fullPath to avoid slice(0, -1).

-      const { params, fullPath } = router.currentRoute.value
-      const { theme } = params
-      const themeIndex = fullPath.indexOf(theme)
-      const linkUrl =
-        fullPath.slice(0, themeIndex) + `${theme}/${type}/${key === 'overview' ? '' : key}${isOpenApi ? '#api' : ''}`
+      const { params, fullPath } = router.currentRoute.value
+      const themeRaw = (params as any)?.theme
+      const theme = Array.isArray(themeRaw) ? themeRaw[0] : themeRaw
+      const themeIndex = typeof theme === 'string' ? fullPath.indexOf(theme) : -1
+      const base = themeIndex >= 0 ? fullPath.slice(0, themeIndex) : '/'
+      const linkUrl = `${base}${theme || ''}/${type}/${key === 'overview' ? '' : key}${isOpenApi ? '#api' : ''}`

56-57: Consider removing the pagehide listener on teardown.

If this composable may be invoked multiple times (hot reload, route re-entry), you can leak listeners. At minimum, guard against double-registration or expose a disposer.

Example:

// outside: let pagehideBound = false
if (!pagehideBound) {
  window.addEventListener('pagehide', client.onPagehide)
  pagehideBound = true
}

Or return a cleanup function from useTinyRemoter.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 87d2ab2 and 5c91e1c.

📒 Files selected for processing (1)
  • examples/sites/src/composable/useTinyRemoter.ts (1 hunks)

Comment on lines +44 to +45
await client.connect(clientTransport)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Double connect call on WebMcpClient — verify supported overload/sequence.

You call client.connect(clientTransport) and then client.connect({ url, agent }). Depending on @opentiny/next-sdk’s API, the second call might be intended, or there may be a specific “proxy/remote” method to use (e.g., createRemoteSession). Please confirm the API contract.

Also applies to: 47-53


🌐 Web query:

Does @opentiny/next-sdk support calling WebMcpClient.connect twice: first with a transport, then with options { url, agent } to create a remote session? If not, what is the recommended way to establish a local message-channel connection and then dial a remote MCP proxy (e.g., createRemoteSession/connectProxy)?

💡 Result:

Short answer: No — you don't call WebMcpClient.connect twice (first with a local transport and then again with { url, agent }). The MCP/next-sdk pattern is to connect the client once to a local transport (MessageChannel / in-memory / stdio), and if you need a remote agent to reach that local client you create a proxy/remote-session transport that exposes the already‑connected client (e.g. createStreamProxy / createClientProxy / createServerProxy). Use that proxy’s transport/session id for the remote side — you do not reconnect the same client with a second connect call. (classic.yarnpkg.com, socket.dev)

Recommended approach (summary + minimal examples)

  1. Establish the local message-channel (or in-memory/stdio) connection
  • Use the MessageChannel transport or in‑memory transport and connect the client once:
    • createMessageChannelTransport / MessageChannelClientTransport (browser-to-iframe/worker).
    • or createInMemoryTransport / StdioClientTransport for local testing. (socket.dev, classic.yarnpkg.com)

Example (browser iframe / message channel)

  • Host page:
    • create MessageChannelServerTransport and listen, then server.connect(serverTransport).
  • iframe:
    • create MessageChannelClientTransport('endpoint'); await client.connect(clientTransport). (socket.dev)
  1. Expose that local client to a remote MCP/agent by creating a proxy transport
  • Use the next / next-sdk helpers that return a proxy transport (and session id) which the agent/server can dial:
    • createStreamProxy / createClientProxy / createClientProxy plugin (stream or sse).
    • These helpers create a Proxy transport (and a sessionId) that you can pass to your agent server endpoint so a remote MCP can connect into the browser client. (npmjs.com)

Example (createStreamProxy flow)

  • After your client is connected to the message-channel transport:
    const { transport, sessionId } = await createStreamProxy({
    client: myClient, // already-connected Client
    url: 'https://agent-server.example/mcp',
    token: '...'
    });
  • The helper returns a Proxy transport object (and sessionId). The agent server (or remote MCP host) uses that sessionId / URL to dial into the transport. You do not call myClient.connect(...) again — you created a new transport that proxies into the already-connected client. (npmjs.com)
  1. Server/agent side
  • The remote side (agent server / MCP host) either:
    • connects to the returned proxy URL/sessionId (streamable HTTP or SSE), or
    • uses the next-sdk server proxy helpers (createServerProxy / connectMcpServer) to accept/dial sessions. (socket.dev, npmjs.com)

Why not call connect twice?

  • The MCP Client API expects a single transport connection (you supply a transport object when you connect). To make that single connected client reachable remotely the library provides proxy transports that bridge that connection to a network URL — that is the supported pattern. Attempting to “reconnect” a client by calling connect again with URL/agent options is not the documented or intended flow. (classic.yarnpkg.com, socket.dev)

If you want, tell me which concrete transports and environment you’re using (browser main ↔ iframe, web worker, Node stdio, or an existing agent server URL) and I’ll give a copy‑paste example for that exact flow (local connect + createStreamProxy + how to call the remote agent with the returned sessionId).

Citations:


Replace double .connect() with a proxy transport helper

According to @opentiny/next-sdk’s API, you should only call WebMcpClient.connect(...) once with a transport. To expose an already-connected client to a remote MCP/agent, use a proxy transport helper (e.g. createStreamProxy or createClientProxy) rather than calling .connect() a second time.

• File: examples/sites/src/composable/useTinyRemoter.ts
– Lines 44–45: keep
ts await client.connect(clientTransport)
– Lines 47–53: remove
diff - await client.connect({ url, agent })
– Instead, import and invoke a proxy helper after the initial connect:
```ts
import { createStreamProxy } from '@opentiny/next-sdk'

// after `await client.connect(clientTransport)`
const { transport: proxyTransport, sessionId } = await createStreamProxy({
  client,
  url,
  agent,    // or token, per your auth flow
})

// use `proxyTransport` to dial the remote, and share `sessionId` with your agent server
```
🤖 Prompt for AI Agents
In examples/sites/src/composable/useTinyRemoter.ts around lines 44–45, do not
call client.connect a second time; remove the erroneous block at lines 47–53 and
instead import and call a proxy helper (e.g., createStreamProxy or
createClientProxy) immediately after the existing await
client.connect(clientTransport). Pass the connected client and the required auth
(url/agent/token) to the proxy helper, receive the proxy transport and
sessionId, use that proxyTransport to dial the remote, and share sessionId with
your agent server so you never call .connect() twice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
refactoring Refactoring (重构)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants